Afrikaans
Akan
Albanian
Amharic
Armenian
Azerbaijani
Basque
Belarusian
Bemba
Bengali
Bihari
Bosnian
Breton
Bulgarian
Cambodian
Catalan
Cebuano
Cherokee
Chichewa
Chinese (Simplified)
Chinese (Traditional)
Corsican
Croatian
Czech
Danish
Dutch
English
Esperanto
Estonian
Ewe
Faroese
Filipino
Finnish
French
Frisian
Ga
Galician
Georgian
German
Greek
Guarani
Gujarati
Haitian Creole
Hausa
Hawaiian
Hebrew
Hindi
Hmong
Hungarian
Icelandic
Igbo
Indonesian
Interlingua
Irish
Italian
Japanese
Javanese
Kannada
Kazakh
Kinyarwanda
Kirundi
Kongo
Korean
Krio (Sierra Leone)
Kurdish
Kurdish (Soranรฎ)
Kyrgyz
Laothian
Latin
Latvian
Lingala
Lithuanian
Lozi
Luganda
Luo
Luxembourgish
Macedonian
Malagasy
Malay
Malayalam
Maltese
Maori
Marathi
Mauritian Creole
Moldavian
Mongolian
Myanmar (Burmese)
Montenegrin
Nepali
Nigerian Pidgin
Northern Sotho
Norwegian
Norwegian (Nynorsk)
Occitan
Oriya
Oromo
Pashto
Persian
Polish
Portuguese (Brazil)
Portuguese (Portugal)
Punjabi
Quechua
Romanian
Romansh
Runyakitara
Russian
Samoan
Scots Gaelic
Serbian
Serbo-Croatian
Sesotho
Setswana
Seychellois Creole
Shona
Sindhi
Sinhalese
Slovak
Slovenian
Somali
Spanish
Spanish (Latin American)
Sundanese
Swahili
Swedish
Tajik
Tamil
Tatar
Telugu
Thai
Tigrinya
Tonga
Tshiluba
Tumbuka
Turkish
Turkmen
Twi
Uighur
Ukrainian
Urdu
Uzbek
Vietnamese
Welsh
Wolof
Xhosa
Yiddish
Yoruba
Zulu
hi everyone welcome to the simplyland
youtube channel this session will be
about python for beginners before we
begin let me inform you about the daily
updates on multiple technologies on our
channel
if you love hunt for technological stuff
consider getting subscribing to our
youtube channel and don't forget to hit
the bell icon to never miss an update
we from simplyland bring you this
beautifully designed organized and
upgraded python full course for
beginners for 2022.
now let's get started with today's
agenda first we will start with the
briefing on python programming language
then we will learn to install python on
windows and write our first program in
python after that we will start with
basic concepts that is variables and
data types in python numbers in python
python object types and type conversion
strings in python and operators in
python
now understanding the basic concepts we
will educate ourselves with if
statements in python followed by the
python loops python loop coding
techniques control statements in python
and conditional statements in python
with that we will develop a good hold on
the basic concepts now moving on
we will start with python lists tuples
dictionaries
and list comprehension in python
followed by python functions and lambda
function
further we will have hands-on map filter
and reduce function in python moving on
we will get ourself educated with
classes in python inheritance in python
iterators and generators in python
string formatting in python scopes and
arguments in python oops concepts in
python and operator overloading in
python
finally
we will be encountering some language
building concepts
that is modules in python
packages in python file handling in
python exception handling in python
and our concluding concept that would be
sorting in python what is python
python is a high-level object oriented
programming language developed by guido
van rossum in 1989 and was first
released in 1991.
python is often called a batteries
included language
due to its comprehensive standard
library
a fun fact about python is that the name
python was actually taken from the
popular bbc comedy show of that time
monty python's flying circus
now
let's look at the top features of python
first so python has a simple structure
and a clearly defined syntax this allows
the learners to pick up the language
quickly so it is easy to learn and use
python can run on different operating
systems such as windows linux and mac
making it a portable language it enables
programmers to develop the software for
several competing platforms by writing a
program only once
third python is freely available at the
official website since it is open source
this means that source code is also
available to the public
now python uses an object-oriented
approach that encapsulates code within
objects
python provides a collection of
libraries for various tasks such as
machine learning web development and
data analysis
and finally in python you don't need to
assign the data type of the variable
when you assign some value to the
variable it automatically allocates the
memory to the variable at runtime
now with that
let's move on to the users of python
programming
so python programming language is used
to develop desktop applications and
build web applications too
it is popularly used in the field of
data science machine learning and
artificial intelligence to analyze data
build predictive models and make
business decisions python is also widely
used in game development
now
let's see some of the popular python
frameworks and libraries
python can be used for web development
using frameworks like xango flask
pyramid and cherry pie
now you can build graphical user
interfaces using libraries and
frameworks such as
tkinter or just kinter
you can also use pi gtk by qt or pygs or
python javascript
now python is also used to perform
machine learning tasks using libraries
such as tensorflow pytorch scikit-learn
matplotlib and scipy
you can also perform mathematical
computations using numpy and pandas
now let's look at the best ids that you
can use to write programs in python and
perform specific tasks
so we have jupyter notebook which is
part of the anaconda distribution that
is widely used these days even for our
demo in this video we'll be using
jupyter notebook i'll show you in a
while then we have the visual code
editor from microsoft this is also one
of the preferred
ides by learners and companies
then we also have the popular text
editor called sublime text editor
then we also have pycharm followed by
python idli and spyder as our top ides
now let's look at the top companies that
are using python in our day to day work
so we have google quora facebook even
netflix spotify and instagram now there
are other top product based service
based and startups that also use python
programming
okay
now with this theory let's
move to our jupyter notebook where i'll
show you how to write basic python code
so i have my anaconda distribution of
python already installed and i'm working
on a
windows system so
i'll search here for
jupyter notebook
you can see here i have my jupyter
notebook anaconda 3 installed let me
just open it
now this will open on a web browser
you see here this is my chrome browser
okay
so
here i have some python notebooks
already created
now for our demo let me go ahead and
create a new one
so here i'm going to
click on new
and then i'll select python3
this opens
in a
new tab
and here i can write whatever code i
want
all right
so first
let's
see how you can print a simple
sentence or a text in python
now to print something you can just use
the print function
if i write print
within brackets suppose i want to print
my country that is india
now india is actually
a string so i need to pass in within
double quotes
so this is it if you want to print
something you can just use the print
function and pass within the function
whatever you want to print
and now to run this cell
i just need to
click on this run button or you can hit
shift enter to run this cell
i'll just hit shift enter
you can see it here it has printed
india for me
all right
now let's say
you want to
perform some
simple mathematical calculations that
also you can do it suppose i want to
find the sum of
10
plus
50.
i'll just run this cell you see here
it gives me 60. it's very simple
similarly if you want to find the
product of
let's say three numbers i'll write let's
say 40 multiplied by 2 multiplied by 5
if i run this
you get the result that is 400
which is correct
ok
now to store our
values we can
take the help of a variable
suppose
if i write x
equal to
7
this means that my value 7 is stored in
the variable that is x
you might be aware that in other
programming languages also we have
variables and data types which i am
going to
tell you now
so here i have assigned my value 7 to
the variable x
now let me go ahead and print what is
there in x
if i run this cell
there you go
it gives me 7 which means x holds the
value of 7.
now if you want to check the data type
of x you can use the type function in
python
so if i write
type of x
and if i print it
it will also result
in the type of data that x is holding
you can see here the first print
statement prints the value of x that is
7 and the second print statement gives
me the type or the data type of x which
says it is of class integer or
int cool
now
let me show you how you can use
the input function to take user inputs
suppose
i have a variable x
where i want to store some
numbers
i'm going to use the
int function and inside the in function
i'll give my input function
so when i run it
it will ask the user to input a number
i'll write
enter
number
x
okay
similarly
i'll just copy this
come to the next line
i want to create another variable called
y
which will have another number i will
write enter number
for y
and then
i am going to
the addition
so i'll write
addition of
x and
y is
give a colon
and then
i'll pass in the operation within
brackets that is x plus y
okay
so essentially what i am doing here is
i am
assigning the value of
my first number to x then i'm assigning
the value of my second number to y and
then i'm finding the
sum of x and y
let me
show you the result if i hit shift enter
it is asking for the user input because
i had defined my input function
so
it is asking
enter number x let me
give my number as let's say 30
i'll hit enter
again it is asking for my
buy input let's say i'll give
60
and then i'll hit enter
there you go it has written me the
addition of
30 and 60 that is 90. you can see the
message as well addition of x and y is
90.
cool
now
let me show you
how to add two strings
and we'll compare the results when you
add two strings and two numbers so
basically
when you add two strings
it is going to merge both the strings or
concatenate both the strings
the way to do is i'll just copy the
let me copy all the three lines of code
from the top i'll paste it here
now i'm going to remove the
integer function that i had used
the integer function was actually used
to
typecast the
input to integer
but now i am going to take the values
in terms of
text or string
now let's see the difference
if i run this
let's say i'll enter my
number as 10 and then
my second number would be let's say 20
if i add 10 and 20
it is going to merge both the numbers
and return me 1 0 to 0.
so
when you add two strings
it is going to return you
the merged value of both the strings
all right
now let's go ahead and explore some of
the popular data types in python
now i am giving a hashtag and typing
data types this means
anything followed by the hash represents
a comment
so
in other programming languages also we
have comments similarly in python if you
want to write a comment you can give
a hash and
pass in the comment
so first let's see i have a variable
a
which has a value of 7
or let's say 10
now if you were to find
the type of
value that a
variable is holding you can use the type
function if i run this it gives me
integer because 10 is an integer
let's say i want to find
the type of value
minus 7 is
now if i run this again minus 7 is an
integer let's say
i want to know
what 3.5 is actually if i run this it
gives me float because 3.5 has a
floating point or a decimal point
similarly let's see
another example i'll write minus 2.4566
if i run this again this is also a float
value
similarly
now let's write a complex number
which has a real part and an imaginary
part
let's say i write
7
plus
10 j
if i run this there you go this is a
complex number hence it has returned
the value is complex
now
if i just write 10 j let's see what it
represents
again it's a complex value
now let's pass in a boolean value
suppose i write true
now true and false are boolean values
so ideally our python should return
boolean only there you go you can see it
has returned us boolean
now let's move ahead and
explore some of the
popular objects in python so we'll start
with
list
list is one of the popular objects in
python
now to
declare a list i'll
create a variable called let's say l1
i'll give an equal to
and within square brackets i'll pass in
my list
list can hold data of multiple data
types
i'll show you now so john here is a
string
i'll give something like 1 0
2 could be the employee id of john
i'll give
usa let's say the
country to which jon belongs to
and i'll give a floating point value
let's say 180.5
assuming it's centimeters and this is
john's height suppose
if i run this
you see i have created my list and if
you
want to print it i'll just write l1
there you go
so here i have my
list l1 printed
now suppose you want to
check the
type of l1
you can use the type function again and
pass in the
variable that is l1
there you go
it tells that l1
has the values in the form of a list
similarly you can create
list
of the same data type let's say
only of numbers
okay
now if i just print l2 you can see
2 has only numbers
similarly you can check the
type of l2
run this it is also a list
okay
now another popular object in python is
called a tuple or tuple
now the only difference between
a list and a tuple is that lists are
mutable which means once you declare a
list you can change the values
while tuples or tuples are immutable
which means that once you declare a
tuple you cannot change the values
now another difference is that
list is written within square brackets
but when you assign a tuple it is within
normal
braces or round brackets as you say
so i'll create a tuple called tup
and within
brackets
i'll
give the values let's say
i want to give the
values of vehicles or cars
so brands of different car we have in
this tuple let's say bmw then we have
audi
next we have mercedes
let's say
jaguar
okay
now
you can use the print statement to print
the tuple
and let's say i also want to print
the type so i'll use the type function
and pass in my variable that is tup if i
run this
you can see the first print statement
prints the
values present in the tuple top and then
we have the type
you can see it is of type or class tuple
now next we have our
third object
which is called a dictionary
i am giving comment here for readability
okay
now dictionary consists of key value
pairs and
again mutable objects just like list
which means you can change the values of
the dictionary once they are assigned
and dictionaries are written within
curly braces
let's say i want to create an employee
dictionary
so i'll give my variable name as
employee
and then
start with my
curly braces
first
i'll give the key
say
the name and then we have the
name of the person in terms of value
that is john
next we have his age
let's say ages 29
now one thing to remember here is the
keys should be passed within double
quotes
and the value is a string you can pass
within quotes
but if the value is an integer or a
floating point
number you don't have to pass within
quotes
let's say i want to have the
salary of john as well
again salary is in terms of numbers so
you don't have to pass it within
quotes
let's say
the third information or the fourth
information i have about
john is the company in which he works
let's say
john
works at oracle
so i have my dictionary defined
now
i'll write print
my dictionary employee
and then
i also want to check the
type
okay
let's print
there you go so the first print
statement prints the dictionary employee
and then we have the
data type of
my dictionary employee that is dict
which means dictionary or dict
the fourth python object we are going to
discuss is called a set
now even
a set is created using curly braces like
how we have used in the dictionary but
the difference is sets do not contain
key value pairs
but
they can only contain unique values now
let me show you what i mean
let's say i want to create a set
that has only unique values of months so
within
curly braces i'll pass in my
month names let's say jan
then i have
feb
then i have mar for march
let's say apr for april
so this is a set
and if i want to print i can just
pass in the
variable name that is month let's run it
okay you can see it here it has printed
my set which is not in an order
okay
now you can also check the
type of the variable that is month
if i run it you can see it here it is of
type
or class set
now the difference i want to show here
is as i mentioned
set can only contain unique values
suppose i have another value of
month let's say february feb
if i run this
i'll remove this
if i run it you can see here
still
my set has only unique values so it does
not consider any duplicate values
all right
now moving ahead we will explore how to
extract certain values from the
python objects we'll be using different
techniques bait indexing or slicing
okay
so if i go to the top i had created a
list called
l1
let me print l1 again
okay so these are the values that i have
in my list
l1
now let's
say i want to print
the first element
in my list l1
the way to do is i'll use my print
statement
i'll give my variable name that is l1
and within square brackets i'll give the
index
let's say one
if i run it
it gives me the value 102 the reason
being
in python the index values start from
zero
so this the first value is at index zero
then the second value is at index one
the third value is at index two and the
fourth value is at index three
so if you have to
find what is there at index
3
i just need to replace
1 with 3.
if i run this
you see it here it gives me
180.5
which we had assumed to be the height of
john in centimeters
now you can also do this without even
using the print statement that is the
beauty of python
if i write l1 and within
square brackets let's say i write
2 if i run this
it gives me usa because
usa is the value that is present at
index 0. so
very important thing to remember while
indexing or slicing
is that the index values start from 0
and not 1. so if you had to find the
value
where john is present
you need to use
0 instead of 1. if i run this it will
return me john
ok
now you can also use negative indexing
let's say i write
l1
-1
you can take a guess
what this will return
if i run this
it returns me 180.5
when you use negative indexing
it will start from the
last position so minus 1
is actually this index
let's say i'll write minus 3
and see the result it gives me 102 which
is fair enough if you start from
the back this is minus 1 usa is at minus
2 and at minus 3 we have 1 0 2
all right
also you can use slicing
let's say i'll write l1
within square brackets i'll give let's
say
from 1
to
3
so i want
all the values present from the first
index which is this
till
the third index but
excluding the third index
if i run this it gives me
102 which is at the first index and then
usa which is at the second index now in
python
the
last index is exclusive it is not
included so in case you wanted to print
180.5 as well we have to change this
from three to four
now if i run this
you get
180.5 as well
okay
moving ahead
there are some basic
functions that you can use
with python objects for example if you
want to
add any
value to your list l1 you can use the
append function
suppose i write l1
dot
append
let's say i want to add the
vehicle or the car
that john has
let's see i'll write append
range rover
if i run this
and let's print l1 again
you can see it here we have appended or
added a new value to our list l1
cool
now you can also use the reverse
function
in python if you want to print the list
in reverse order
so let's see
i want to print the elements present in
l1 in reverse order
i just need to write my variable that is
l1
followed by dot and the reverse function
it's very simple
if i run this
and i will print l1 now
it prints my list in reverse order here
it was from
john all the way till range rover
once i reverse it it starts from range
rover and all the way to john
cool
similarly
you can
also
extract specific values from tuples and
dictionaries let me show you
i'll just go to the top and
okay so we had created a tuple called
tup
let me print that tuple again
so these are the values of the different
brand of cars we have in the tuple
let's say
you want to find
the car that is present in the second
index so you can just write
2 within square brackets
so i have my double name followed by the
square brackets and then i have my index
if i run this you get more cities and
again
in python tuples the index values start
at zero and not one so bmw is at index
zero audi is at index one mercedes is at
index two you see it here and then
jaguar we have it index three
again you can use slicing by using colon
and you can also use
negative indexing let's say i'll change
the value from
2 to let's say -3
see the result you see here we have audi
because this is minus one
mercedes is at minus two and aud is at
minus three
okay
now
you can extract the values in the
dictionary
by using the keys in the dictionary
let me go to the top and
see the dictionary that we had created
it is employee let me print it
now in jupyter notebook you can also use
the tab to auto complete a variable name
or a function name
is one of the features that jupiter
notebook provides
so here we have the employee
dictionary
and let's say
you want to
the value
of salary
the way to do is
i'll write print
employee
dot i can use the get function
and within the get function
i'll pass in my
key for
salary
if i run this you see here it gives me
2 lakhs 50 000 which is the salary of
john
similarly if you want to let's say
update any value in the dictionary you
can use the update function
suppose
i want to update
the company of john
from oracle to let's say
the way to do is
i'll write
my dictionary name that is employee
followed by the update function
and then within curly braces
i'll pass in
my key that is company
give a colon
and change it to
let's say google
now
i can just
print my
employee dictionary
there you go
so from company oracle we have changed
it to google now
so these are some of the very
crucial features or important features
that are available in python which helps
you do
a lot of calculations and data
manipulations
all right
next
let's see how to use
an if else
condition or any file statement in
python
like in any other programming languages
be it c c plus plus or java you have if
else statements
in python also we have a full statements
so basically you check some condition
and return a value
suppose i have a variable called a which
has a value of let's say 400
and then i have a
variable called b which has a value of
250 okay
now
i'll use if condition i'll write if
b
is
greater than a
then
b
is
greater
now you will
also have an else statement i'll write
alif which means else
if
a is equal to equal to b
colon then
a and b are equal
finally i'll write my else statement
else
a
is
greater
so what i am doing here is i have
assigned two variables a and b to value
400 and 250 respectively then i am
writing an if else condition so i am
checking a condition
if b is greater than a which means i am
comparing if 250 is greater than 400 in
case it is true then print b is greater
else if
both the values if they are same then
print a and b are equal
otherwise print a is greater
let's run it and see the result
this is fair enough
it prints me a is greater because
b is not greater than a so 250 is
definitely not greater than 400
so this
condition fails even the alif condition
fails only the final condition else is
true that is a is greater than b
so this is a simple example
of using the files
condition of the file statement in
python
now moving ahead
let's see how to use a while loop in
python
now using the while loop you can execute
a set of statements as long as a
condition is true
let me show you a very simple example
i'll write
i equal to 0 so i've assigned value of 0
to i
then i'll write while
i
is less than
8
then
i am going
to
add
i so i'll write i equal to
i plus 1
i'll use another condition if
i
equal to equal to
4
give a colon
and then i am going to use a statement
called continue
i'll print i
so
using the continue statement you can
stop the current iteration and continue
with the next iteration
let's print the result and see
okay
so here
we are checking if i is less than 8 so
first value is 0 0 is less than 8 then i
am incrementing the value of i to 1 so i
becomes
1 now so from 0 it becomes 1
then i am printing i
this condition continues
until we have the value of i equal to 4
so if the value of i is equal to 4 i am
skipping the current iteration so if you
notice the result after 3 we have 5 so
we have skipped
printing 4 and
gone to the next value of i which is 5
so the loop runs till this condition
fails
so
when i is
not less than 8
the loop terminates
all right
finally in our demo let's see how a for
loop works so a for loop is used for
iterating over a sequence that is either
a list a tuple a dictionary a set or a
string
so let me go ahead and create my tuple
tup
equal to
let's say i have
the same brand of cars we have bmw
then i have audi
let's see i have
more cities
i have
jaguar
and then
i have bmw again
all right
i'm going to print
the values present in the tuple one by
one so for that i'm going to use a for
loop so i'll write for
a variable x
in
my tuple
i'll say
print x
so what it will do is
this randomly assigned variable x will
iterate through all the elements in the
tuple and print them one by one
let's hit
shift enter to run it there you go you
can see here i have all the
different
car brands printed one by one
cool
so this brings us to the end of our demo
session on introduction to python let me
go to the top and tell you what we did
so first i told you how to print any
set of statements or any string text
numbers in python you just use the print
statement or the print function
you can also perform very
simple mathematical calculations using
python
then you can also check the data type of
the variable using the type function
then we saw how to use the input
function here we inputted an integer and
then we found the sum of both the
integers x and y the value was 90.
in the next example we removed the
integer function by considering our
values as strings and then we saw the
difference in the results so when you
use strings
the addition operation will concatenate
or merge both the strings or the numbers
then we saw the different data types we
saw
about integer data types about floating
data types boolean data types
if i scroll down we saw
the important
python objects like list
then we had
tuple then we saw how to write a
dictionary how to create a set then we
saw the difference between
list and tuples and even
how set can take only
unique values
then we used some
indexing operations to extract specific
values from lists tuples dictionaries
we also
learned some of the important functions
these are all inbuilt functions that
python gives us
to perform manipulations and operations
in python
so you used append then we saw how to
use reverse
now let me just go ahead and show you
another
function an inbuilt function in python
i'll just insert a
cell below this
suppose you want to find the length of
your list
you can use the length function or len
function that is
inbuilt in python i'll just pass in
ln followed by
my
list that is l1
if i run this
it gives me the result 5 because you can
see it here
my list has 5 elements in it you can
count it so the length becomes 5.
similarly you can also
check the
length of the tuple
let me insert a cell here as well
suppose i write lin
of my tuple that is tup if i run it
again
it says 5
now this was the earlier tuple that we
had created
later we actually created
another tuple
let me show you
okay so this was the tuple it has
taken this new tuple which has five
values in it so the length becomes five
let me go to the top
okay and after that we learned how to
use if else
followed by how to write a while loop
and then finally we saw how to
use a for loop in python
in this session we will learn how to
install python and install numpy scipy
matplotlib and pandas libraries then we
will install the anaconda distribution
in our system
so let's start
as you all know python is an interpreted
language so you need to install a python
interpreter so for that we will go to
the browser
and search for python dot org
now we will move to the downloads page
and choose the latest version of python
to download and the latest version is
python 3.9.5
we'll click on the download
once the installer has downloaded open
it
now you can see the installation window
for python
you have to double check both the boxes
add python 3.9 to path
and click on install now
as the installation completes you can
see a screen that says the setup was
successful now click on close
now to check whether the python has been
installed successfully on the system or
not we will run a command on the command
prompt let's open the command prompt
click on start
and write cmd
now to check whether the python is
installed or not we will run the command
python minus minus version
python space minus minus
version
and press enter so here we can see that
python 3.9.5 version is installed in the
system so yeah python is working in the
system now we'll run some commands for
python
so for that first we will type py
and press enter
and now we will write the basic command
that is
bracket
hello world
semicolon and press enter
as you can see hello world is printed
here so yeah python has started working
in our system
now we will install libraries of python
we will be using pip to install numpy
sci-fi matplotlib and pandas library and
before installing the libraries make
sure the latest version of pip is
installed in your system so to check
that we will run a command in command
prompt
we will open the command prompt
and write a command
pip space minus minus version
and press enter
as you can see the pip version is
21.1.1 and it's being downloaded with
the python 3.9 so it's the latest
version we have downloaded
so now
we have to keep one thing in mind before
installing scipy matte protlib and
pandas library first we need to install
numpy library
so for that we will run a command
pip
space
install
numpy
and press enter
depending on your internet speed it will
get installed
as you can see the numpy library has
been installed and there's a warning
that our pip version is 21.1.1
and we should upgrade it to 21.1.2
that is the latest version available so
we'll upgrade the pip version for that
we will write a command
python
space minus m space
pip space
install space minus
upgrade space
pip
enter
okay so we made a mistake here in the
command so the mistake is we have
written only one minus sign before the
upgrade we have to write two minus signs
before the upgrade
so we'll write the command again
python
space minus m
space
pip space
install space minus minus upgrade
space
pip and then press enter
and now depending on your internet speed
the pip version the latest version will
be installed on your system
as you can see they have uninstalled the
pep version 21.1 and they have installed
the latest version that is 21.1.2
we have installed the first library that
is numpy and that's the basic
requirement
for the installation of scipy library so
now we will install the scifi library
so for that we will write the command
pip install scipy
pip space
install
space sci-fi and press enter
and depending on your internet speed it
will be downloaded
now you can see that the scipy library
has been installed successfully and here
you can see
that the requirement already satisfied
numpy so we have firstly downloaded the
numpy library so that we can easily run
the scipy library
now we will download and install pandas
library for that we will write the
command
pip space install
pandas
and press enter
and this will also
install depending on your internet speed
we can see that the pandas library has
been successfully installed now we are
left with matplot lib library so now we
will install that for that we will write
the command
pip space
install
mat
load lift and press enter
as we can see the matplotlib library has
been successfully installed
now we have installed all the four
libraries
so if you want to check whether the
library is installed on your system or
not
you can write a command to check that
first you have to write python and press
enter
first we will check for numpy library
and for that we will create a array
for that we will write the command
import
numpy
s and p and press enter
if you don't get any error it means that
the library has been installed
successfully so now we will create an
array
a equal to
np dot
array
1 comma 2 comma 4
comma
5 comma 7 comma
9
comma
d type
equal to
we'll set it for float
press enter and we want to print this
array
like print
array
created
a
and press enter
you can see the output error created one
two four
and five seven nine
so the numpy library is working fine
so we will check for other libraries for
that
we will write
import
space
mat port live
and press enter
if you don't get any error it means that
the library has been installed
successfully
so for the rest also we can
write the same commands import
pandas and press enter
we do not get any error so the library
has been installed successfully and we
are left with sci-fi so we'll write
import
space sci-fi and press enter
so here also we didn't get any error so
the library has also been installed
successfully
now we will see what anaconda is
anagona is a free and open source
distribution of python and our language
here we have conda which is a package
manager system similar to papen python
so now we will see how to download
anaconda and then we will explore its
features
to download anaconda first we will open
the browser
and search for the keyword anaconda
we have to visit the official website
that is www.anaconda.com
and now we will click on the products
section and choose the individual
edition as it is open source edition and
it is free of post
now we will scroll down
here is the toolkit for the individual
edition and will click on the download
on clicking the download we are directed
to the bottom of the web page and here
we can see the different versions
available for windows that is 32 bit and
64 bit
we will download the 64 bit and it is of
size 477 mb so it will take ample amount
of time to download
we will download it
as the download completes click on the
application file
now click on next
the license agreement will appear
now click on i agree
then you have to select the installation
type
if you want to install for a single user
click on just me
i'll select for all users and click on
next i am installing for me
so i'll click
next
then it will ask for installation
location
after selecting location click on the
next
my for me the location is fine so i will
click next
then advanced installation options will
appear if you have already installed
python on your system as we have
installed already so we do not have to
click on this section
we will only click on this section and
press install
it will take time to install
after the installation is complete click
on next
then click on next
and uncheck both these options
and click on finish
as you can see the installation has been
completed
now
we'll go to start and type anaconda
we can see that
anaconda prompt and anaconda navigator
are visible
first we will open anaconda navigator
it's initializing and adding features
here you can see some pre-installed
applications
and tools that are already installed in
the anaconda
and if you want to install any other
tool you can
like you can install our studio python
professional orange 3 blue is
in the anaconda
and you already have spider qd console
powershell prompt jupiter notebook
jupyter lab ibm watson studio cloud
datalore cmd.exe prompt
so now we will open an upunder prompt
now let's see which version of conda is
installed in the system for that we'll
write a command conda space info
and press enter
here we can see that the corner version
is 4.10.1
now we will launch jupyter notebook for
that we will write the command
jupyter notebook
and press enter
you can see that the jupiter notebook
has initiated
now create a folder where you want to
store the projects and rename
accordingly
so to create folder
will create the folder in onedrive
sorry
i will create the folder on desktop
new
folder
we will click the untitled folder
and rename it
and rename it as
python
1
now minimize the window
and
open the desktop
you can see that the python one
directory is created
and now we will click on the python one
folder
and create a python 3 notebook
as we have created a python 3 file in
the jupyter notebook now we can run the
python commands on it so we will run
some commands
and first we will run a basic command
that would be print
india
and we will run this command media is
printed here
i'm going to run some
operators
like we will
7
into eight
and
the run so it's 56
and we'll also run an exponential
operator
to 6.4
so you can see
16 the result comes out
so now to save this file first we'll
rename it
demo one
rename
and we will save it
save and checkpoint
now you can check in the directory you
have created python one
that it is being saved as demo1 in this
session we will learn to write a program
in python ideally then we will see a
program to add two numbers and
afterwards we will run a program in
jupyter notebook
as you all know python is an interpreted
language so we require a python
interpreter to work upon while
installing python in our system we also
get python idi automatically installed
but before writing a program in python
ideally we will write a program on
command prompt
so for that first we will open command
prompt
we will click on start and write cmd
and click enter
now the command prompt appears
first we will check the python version
pip space minus minus version
and press enter
you will see the python version 3.9
now
we will start writing the python program
for that first we have to write the
command p y and press enter now we can
start writing our program
we will write a basic program on
division
for that we will assign a value
5
to a variable a
and
value 10 to the variable b
and we will divide b
by a
and we'll print the value
of c
press enter
as you can see we have got an output 2.0
now we have run a program on command
prompt successfully now i will write a
program in python ideally
so to write a program in python idli we
will see some steps
first we have to open the python ideally
then click on file menu and choose the
new file
and
after writing the program we have to
save the program with dot py extension
and then we can click on the run menu
and then we will see a run module and we
have to click on that
now we'll see it practically for that we
will click on start
and search for id ali
and now we'll click on python ideally
now we will follow the steps as we have
seen now
we will click on file menu and choose
new file a new window will appear
here we will type the program to get two
numbers inserted by user and add them
but before writing this program let's
understand this program
so python program on adding two numbers
first we have to get an int value
inserted in variable a for that we will
write the command a equal to
int
round brackets input round bracket
started for the message we have to put
it in inverted commas and the first
number colon round bracket close and
another round bracket close
now we will insert an end value in
variable b
for that we will write the command b
equal to int round bracket started input
around bracket started for the message
we will put the message in inverted
commas and the second number colon
and then we will close this message
by round bracket and another round
bracket closing
then we will assign a variable c
and add the operation a plus b for that
now we'll print
a message that would be addition of two
numbers equal to that would be an
inverted commas
comma c
as c variable will store the result of a
plus b
all the statements in the program will
get executed line mainly now we will
execute this program on python ideally
so for that we will write our program
here
that would be a equal to
and
round bracket start
input
round bracket
inverted commas
enter first number
invited commas close
round bracket close
be equal to
end
input
round bracket started inverted commas
for message
enter second number
inverted commas
round bracket close
now we will assign the operation a plus
b in variable c for that we will write c
equal to a plus b
and now we will print c
before executing this program we will
save this program file
save as
we will save it as demo1
and we will write the extension py
and press save
as the program is saved now we will run
this program by click on this run menu
and then click on run module
you can see the program has been
executed now we will write the first
number that would be 10
press enter and second number will write
6 and press enter we will get 16 as an
output
so we have executed the program on
python ideally
now we will see some best python ids
in the market
for that
the best python ids in the market are
jupiter notebook visual studio code
sublime text pycharm
python ideally and spider notebook among
all these ids we have worked with python
ideally now we will write a program in
jupyter notebook
for that you have to install jopeta
notebook
i have installed anaconda distribution
and it has python id already installed
if you want to know how to install
anaconda distribution go and check the
video in python playlist
so let's open jupiter notebook for that
first we'll click on start
and write
jupyter notebook
and click on the jupyter notebook
anaconda 3
and we will wait to get it started in a
browser
now we'll select the location where we
want to store the program
we will select the location in onedrive
desktop
and i've created a python 1 folder there
so here we'll create a new python 3
notebook
and
name it as
first python
program
and now here we can start writing a
program
here we will write a program to multiply
three numbers
so for that we will get all the three
integers inserted by the users in three
variables and then we will operate the
operation multiplication
so for that we will write the command a
equal to end round bracket started
input
round bracket and here we will print the
message
enter
first number
colon
and then
noted commas clause and the round
bracket clause now we will enter
another integer in variable b
for that we will write the command equal
to end round bracket
input
round bracket started inverted commas
enter second number
colon
and then we will close the inverted
commas and the round brackets
and now we will get the third integer
inputted by the user in variable c for
that we'll write the command c equal to
in
round brackets input round brackets
inverted commas
enter
third number
colon
inverted commas close and round bracket
close now we will assign the operation
of multiplication in variable d
that would be by the command d equal to
a
into
b
into c
now we'll print the variable d
and for that we will also print the
message
multiplication
of three numbers
and close the inverted commas and then
we will
insert a comma and then write the
variable d
as d contains the output of a into b
into c now we'll click on the run
command
and now we will enter our first number
that would be
five
and press enter then the second number
four
then the third number six and then press
enter
and then we will get the output of
multiplication of three numbers as 120.
now we have successfully run the program
on jupyter notebook so in this video
we will learn what is a variable in
python
then
we'll understand what are object
references
we'll also see the different rules for
python variables and finally
we'll understand variables in detail
with hands-on demonstration on the
jupyter notebook
so variables in python hold an object of
a particular data type python variables
are containers for storing data values
we do not need to declare variables
before using them or declare that data
type like we do in other programming
languages such as java or c plus plus
python is not statically typed
a variable is created the moment we
assign a value to it
a variable is a name given to a memory
location
so here we can see
we have a variable called car and it has
a value called bmw now this value is of
type string since it is written within
double quotes
variables can have values of multiple
data types
now python also allows you to assign
values to multiple variables in one line
so here you can see i have assigned
x y z to audi bmw and mercedes in one
single line
all right
now let's look at object references in
python a python variable is a symbolic
name that is a reference or pointer to
an object
once an object is assigned to a variable
you can refer to the object by that name
so here we are assigning an integer
value of 50 to the variable a
so assignment creates an integer object
with a value of 50 and assigns the
variable a to point to that object as
you can see here so a is the variable
and it is pointing to the object that
has 50 value
now let's see another example so in this
case
we have
assigned
a variable a which has a value of 50 and
then we have created another variable
called b
that has the value stored in a
now python does not create another
object in this case
it creates a new symbolic name or
reference called b
which points to the same object that a
points to
so here you can see
both a and b
are pointing to the same object that is
50.
okay
now
in this example
python creates a new integer object with
a value of 100 and b becomes a reference
to it we will explore all of these in
our demo
now
there are some rules for python
variables
let me just
read all the
and we will explore all these rules in
our demo session
so first a variable name
must start with the letter or the
underscore character
a variable name cannot start with a
number a variable name can contain only
alphanumeric characters or underscores
so you can see from a to z 0 to 9 or
just underscore
variable names are case sensitive so
here you can see i have written
date
in three different types and
these
are read as different variables and not
the same variable
and then
there are several techniques to write
multi-word variables you have the camel
case you have the pascal case and we
have the snake case don't worry about it
we'll explore these
in the demo
now let me take you to my jupyter
notebook where we will understand
variables in detail
okay so i am on my jupyter notebook and
i have
my title as variables in python
so let's start
with my first variable let's say i have
a variable called a and i am assigning
50 to it
now you must be aware 50 is of type
integer
so
this a variable is now
holding an integer value
now if you want you can just print a
if i hit shift enter
it will give me the value of 50.
now to check
the data type of a you can use the type
function now we have covered data types
in detail in our previous video if you
want you can have a look at it
so i will write type of a if i hit shift
enter it gives me the integer type
okay
now
let me show you another function called
id if i write id of a
let's run it it gives me a number this
is a long number
now the id function in python returns a
unique id for the specified object so
here object is a
so all objects in python have its own
unique id
the id is assigned to the object when it
is created
now what if
i assign
100 to a this time and let's see
the id of a
if i run it you can see here the values
are different than the previous one
so every time the id function will
return a unique id for the specified
object
all right
now
we learned in our theory section that
you can assign multiple variables in a
single line now let me show you how to
do it
suppose
i'll write x
comma y comma
c
so these are the three variables
and i want to assign
three values to them
so let's say x will have 50
in y i want to store let's say
168.6
and
my z
will have
a string or a text value let's say
simply loan
all right
let's run it
okay
now you can
print them one by one
you can see here x has 50
y has
168.6
and z has
simply learn of type
text you can check the
data types if you want let's say i want
to check the data type of y
it gives me a float because 68.6 is a
float
you can check the data type of
z
it is of type string
okay
now you can also perform the same
operation of assigning
multiple variables in a single line in
another way let me show you how to do it
suppose i want to assign
the same
value to three different variables let's
say i want to assign the value of 10 to
x y and z
so i'll write
x equal to y equal to z equal to
i'll write 10.
if i run it
and let me print them one by one you can
see here x is 10 y is 10 and
z is also 10.
now there is
another way to do it that is
i'll pass in my variables x comma y
comma z
and then
i can write 10 comma 10 comma 10
this will return the same result
okay
now let's look at the
rules for writing variable names
so these rules we had discussed in the
pbt section
now we'll explore them one by one so the
first rule is a variable name
must start with a letter or the
underscore character
so
let me just give a comment first
rules
for variable
naming
so the first rule says a variable name
must start with a letter or the
underscore character so if i write let's
say
some random variable name abc equal to
100
this is
valid you can print it
abc it gives me 100.
now
you can also write the variable name as
a
followed by any number
it should be integer number
if i write 102 equal to
let's say
this time
i'll
give a string let's say
india and let me print it
it works perfectly fine
now we also said the name must start
with an underscore
i can start with an underscore and then
write let's say 123
is equal to 70.5
now let me print it
now this works as well so you can start
your variable name with an underscore
followed by a letter or numbers
let me show you another example this
time i follow the underscore with
letters let's say
dog
i'll just give
any random dog name let's say i have a
dog called puppy
and let's see i'll print it
this also works
okay
now
you can have multiple underscores in
your name as well
suppose i'll write
underscore
name
underscore each
this is my variable name
i'll write
let's say
stuart
36
and let me print it
i'll write underscore name underscore
age
this is also a
valid variable name so you can have
multiple underscores in your variable
name
now
the next rule is a variable name cannot
start with a number
so if i write
let's say 4
name equal to
gilly
and if i try to print it
it will throw an error so you cannot
have a variable name starting with a
number
all right
now
let me
scroll down
the next rule is a variable name can
only contain alphanumeric characters and
underscores
so if i write at the rate
then let's say
age
equal to
40 if i run this
it throws me an error because at the
rate is not recognized and it is not
a valid variable name
similarly let's say i'll write
name
dollar
age
equal to let's say 40
again this is not recognized dollar you
cannot use it in your variable name
the next rule is
variable names are case sensitive
so suppose i have a variable called car
which is all in lower case
and
my car has a value let's say bmw
now if i were to print car it gives me
bmw
suppose i have another variable which
starts with a capital letter
c followed by lowercase ar
if i were to assign
car to let's say tata
and i print it
it returns me tata and not bmw so you
should keep in mind that variable names
are case sensitive
now similarly i can also have a variable
in all upper case let's say
my
car is of toyota brand
i made a spelling mistake
okay now if i print car
it gives me toyota
so
these are the different
types of using case sensitive variables
now another important
thing to note is
in python reserve words cannot be used
as a variable name
so let me open a new tab and here you
will search for
reserve
keywords
in python
let me open this link
or any other link for your reference
you see here
these are all
your keywords in python and these cannot
be used as variable names let's try
using a few of them let's say i'll use
break
let's assign
a value to variable break equal to let's
say
60 if i run it it gives me an error
invalid syntax break you can't use
similarly let's use
another keyword let's say i'll use for
this time
we have a keyword
called for you can see it here
suppose i write
for
equal to
i have
let's say virat
if i run this it throws me an error
again
let's try one more keyword
do we have try as a keyword yes we have
you can see here try is a keyword
if i write try equal to
any random value i'll pick this time i'm
giving a floating number let's say 140.5
if i run it again it throws me a
error
but
you can use
an underscore and then
you can give that keyboard let's a try
i'll assign the same value
and let's say we'll print it this will
work fine since
the variable name is no more a keyword
because we have an underscore
in the beginning
ok
now let me show you some
basic operations that you can perform
on python variables let's say we have
a equal to 100 and let's say b equal to
200
you can assign
an operation to another variable called
result let's say i want
the operation to be an addition
operation
and let's
go ahead and print result
you can see it has given us 300 because
in result we are storing
the addition of a and b so 100 plus 200
is 300
now similarly
you can perform
many operations like let's say this time
we'll perform a subtraction operation
so this time i'm storing
a minus b in result and let's go ahead
and print result you can see here 100
minus 200 is minus 100
then you can also have
let's say result equal to
a
by
b
and let's print it
fair enough we have 0.5 because 100
divided by 200 is 0.5 similarly you can
also have
integer division suppose i write 100
divided by
say 40
and i'll
print the result
you see here it has given us 2.5 but
what if i want to perform an integer
division so i'll add
one more forward slash here and let's
run it it gives me only two so it has
truncated the 0.5
okay
now moving ahead
let's say i have a variable called
country
and
i have
india in it
so country is my
variable name and it is pointing to the
object that has
india as the value
i can print the
variable
you see here i have india
and now if you want you can perform some
extraction operation
suppose if i write country
within square brackets if i write
3
it gives me
the character that is present at the
third index so i is present at the 0th
index n is at the first index d is at
the second index and i is at the third
index let's say i want everything that
is present
until the third index it gives me ind
so this 3 is exclusive it will only
return us
the values present at the zeroth index
the first index and the second index
okay
now let me show you another interesting
example
suppose i have a list that is called
cars
and i have a list of
car names
let's say i have
bmw
then i have
ferrari
and let's say
i have toyota
i'll run it and i'll print my
list that is cars you can see here
there are three car names
and now what if i want to
put each of these car names in different
variables so i can write x comma y
comma z
and
i'll write equal to cars
if i run this
now what it will do is it will assign
each of these values to
x y and z respectively now if you want
to print x you can see here
x has bmw then y has ferrari and z has
toyota
so this is another way to assign
values to variables
from a list
okay
now
you can also
use variables in the print
function or the print statement suppose
i write x
equal to let's say it has simply learned
now
i can print a message let's say
welcome
to
i'll give a space
close the quotations
give a plus sign and i'll give the
variable name
if i
run it you can see here
the message is printed welcome to
and the x which has the value of simply
loan so welcome to simply loan okay
now another thing to note in python is
that you cannot add an integer and a
string suppose i have x as the variable
and it has a value let's say 20
and then
i have y which has
the string simply learn
now string can be put in double quotes
or in single quotes you can use
whichever way you want
suppose i print
x
plus y
let's see the result
it gives us an error so you cannot
or add
an integer and a string so you need to
convert one of these
values
now there are several techniques to
write multi-words variables
you can use the camel keys to write
multi-word variables
so here each word except the first
starts with a capital letter
so i'll just give a comment here and
write
camel case
and
the way to write is
apart from the
first word
all the words
start with the capital letter
suppose i write my department equal to
marketing
so here
the first word my
the m starts with a small letter while
the second word department the d starts
in a capital letter so this is an
example of a camel case
if i
want to print it i can write my
department
and run it it gives me marketing
let's see another example
i have let's say car brand
so you see here
car brand are two words
but
the first word starts with a
small letter while the second word has
an uppercase
b
let's say my car brand is hyundai
now you can print it
there you go all right
moving ahead
we also have
pascal case where each word starts with
a capital letter
suppose
i have a variable called my name
is
let's say nathan
here you can see my and name are two
different words and
both the words start with a capital
letter so this is an example of pascal
keys
if i run it
let me just print it first okay you see
here i have my name similarly let's say
we have another pascal case
multi-word variable which is age now
where
age has a caps and now
has n caps so this is also an example
of a pascal case variable let's say my
age now equal to 30
i'll print each now
it returns me
30.
now one thing to note here is if i write
let's say age now
if i do this it gives me an error
because your variables names are case
sensitive so we haven't created any
variable which
has small a and small n in each now
okay
now
the third way to write a multi-word
variable is called as snake case
so
if you want i can
give a comment
saying snake case
so here each word is separated by an
underscore character
so let's say i have a multi-word
variable which is city underscore
address
and let's say the city is
new york
now if i print it
you have new york so this is an example
of a sneak case where
each word has a
underscore in between you can have
multiple underscore between each word
suppose i write my
current
age
equal to 35 let's say
so i have
my current each
i run it
okay there is some mistake here i have
missed an r
you see here it says 35 so this is also
an example of a snake case where each
word is separated by an underscore so
here we have two underscores
all right now let me go to the top and
let me brief you what we did so first we
saw an
integer
value variable
we saw how you can check the
data type of the variable using the type
function then we explored about the id
function
we saw how you can
pass in
variables or multiple variables in a
single line
then
we saw how you can assign the same value
to three variables in one line
now this is another method to do the
same operation
now
then we looked at the
different rules for naming variables
your variables can start only with a
letter or an underscore
and that letter can be followed up with
numbers as well and you can have
similarly numbers after
underscore you can also have characters
after underscore
you can have multiple underscores
but your variable name cannot start with
a number
and it cannot have special characters
like
at the rate or
dollar symbol
these will throw an error
now you can see
your variable names are case sensitives
so here we defined car in three
different ways
and all the three
give us different results
another important thing we saw was
you cannot use
keywords python keywords as variable
names we saw break for and try
now we perform some
basic mathematical operations we also
saw how
you can perform some extraction
operation using string values in python
then we saw another way to
assign the values of a list to different
variables
we saw how you can use the variable name
in a print statement
then we saw how
you cannot add an integer
with a string
we explored the camel case
then we saw
how you can
write multi-word variable using pascal
case and finally we looked at
snake keys
so in python
every value
has a certain data type
the variables in python hold an object
of a particular data type
since everything is an object in python
data types are actually classes and
variables and instances of these classes
now there are various data types in
python
first we have the numeric types which
are essentially numbers so under numeric
types we have integers floating point
numbers and complex numbers
then we have x type data which are in
the form of strings
the third type of data that is available
in python are called as sequence types
which consists of less tuples and range
we have already seen about lists and
tuples in our previous video
and in python we also have dictionary
objects as mapping data types
in the previous video you saw how to map
key value pairs using dictionaries
next
we have set data type now sets are
unordered collection of unique items
python also supports boolean data types
and finally we have
binary types of data which include bytes
byte array and memory view
now let's head over to the jupyter
notebook where we will learn about these
data types in detail
so here i am on my jupyter notebook and
i have titled my notebook as data types
in python rec is for recording
so let's first start with numeric data
types
i'll give a comment using
a hash tag
i'll write
numeric
data type
okay
let me define a variable called num
in which i'll store a value of seven
now let me go ahead and print
the data type of
my variable num so for that i am using
my
function as type
if i
run this using shift plus enter you can
see here it tells me that
num variable is holding a value of type
integer
now you can also
use a print statement
i can write something like print
num
comma
i can give a message as ease of
type
i'll give another comma and then i'll
use my function type of
num
let's see the output
you can see it here
it
first
gets the value that is stored in the
variable num so 7
is of type and then it prints the
classes of type class integer
all right
i've just increased my
size of the notebook
next
let's declare
the same variable num and this time
we'll store the value as let's say 10.8
now you can see here there's a point
which means
this is a decimal
or a floating value if you can check the
type of num it gives us
num is holding a value of type float
now let's say
i'll take a negative number let's say
minus 10.8 and we'll see the type of
num
again minus 10.8 is also of type float
now let's say i'll declare
a complex variable let's say
8
plus
6
j
now this is
a complex number
which is again of type
numeric data type
if i want to check the
data type of num it gives me complex
because 8 plus 6 j is of
complex data type
okay
now if you want to extract the
real and the imaginary
parts of a complex number you can do it
something like this
you need to pass in the variable name
followed by a dot
and
the attribute name
is real to extract the
real part of the complex number if i run
this you can see here it has returned
the real part of the complex number
which is 8. now if you want to print the
imaginary part you can use num dot
imeg which is for imaginary if i run
this there you go it gives us the
imaginary part which is 6
okay
now in python you can also perform
conversion of data types so you can
convert between different data types by
using type conversion functions such as
end float str etc
so let me define a
variable called num
which has a value 7.8
now
what i am going to do is
i'm going to create a variable called b
which is going to store the
integer part of num which means
initially i had defined num as 7.8 which
is a floating point number i want to
convert this num to integer type now
and
let me go ahead and
my b and i also print
the type of num
and
i'll then print
the type
b
let's
run this and see the result okay
so if you see here clearly
when i see
print b it has returned me 7 which is of
type integer so it has truncated the
decimal part
present in 7.8
again if i print type of num so num is
holding 7.8 it is of type float after
converting the float value into integer
it has given me int
okay
similarly
let's say we have another
number
minus 90.5
and
if i were to check the
type
i would write print type of num
then let's convert
this to integer
so i'll write print
in top num let's see the results okay so
initially minus 90.5 is of type float
after we converted
our
num
to integer it gives us minus 90 so it
has truncated the decimal point part
all right
now let's say i'll create another
variable let's say c equal to
let's say i'll write float
of
b
now if you remember
our b
holds a value of 7 if i were to convert
b to float again
i can use the float type conversion
function and let's go ahead and print
c
if i run this you can see here
previously
b was holding an integer of 7 now it has
converted that integer into a float
value so it is 7.0 now
okay
now moving ahead
let's see
about
boolean data types
so if i have a variable let's say
r
equal to
let's say it has a value called true
which is a type of boolean value
and let me go ahead and print the type
of r
it gives me
boolean
now let's say i'll write
num greater than c
let's
go to the top if you see here
num is holding a value of minus 90.5
and my c is holding a value of 7.0 i am
checking
if num is greater than c if i run this
it gives me false because
minus 90.5 is less than 7.0 and not
greater than 7.0
suppose
i create a variable
boolean or b double o l
and i'll store that value
num greater than
c
and let's
the type of boolean
i'll use type
of my variable that is bull
let's run it you can see it here it
tells us that
this particular operation is now holding
a data type of boolean
if you are getting confused we can
change the
variable here let's say i'll write
b underscore bull
and similarly i'll write here b
underscore bull
let's run it
you get the same thing
all right
now moving ahead
let's
explore how
string data types work in python
i'll give a comment as
string data types
scroll down
ok
so string data types or string values in
python are passed within
quotations suppose i have a string
called str1
and it has a value let's say
python programming so this is a text
value
i have another string let's say str2
which has a value
let's say simply learn
now
let's run this
okay
now if i were to check the type
of str1
it should give me string so str here is
a string
now you can also perform extraction
operations from the string suppose you
want to extract
the value that is present in my first
string that is str1 at index number five
let's run it
okay there is some error here
okay so this should be str1 and not strl
let's run it again
it returns us n
now let's count what is present at the
fifth index
so from our previous introduction to
python video you might be aware that in
python the index number starts with 0 so
if you count
p is at index 0
y is at index 1
t is at index 2 h is at index 3 o is at
index four and then
n is at index five so hence str one of
five returns and
similarly if you can
check for
other string that is string two let's
say i want to see the value that is
present
at minus
four
let's run it
it gives us e
now if you use a negative indexing
operation it will start counting from
the backward position so here
n is at minus 1 r is at minus 2 then you
have a
at minus 3 and e is present at -4 so
hence str2 of minus 4 returns e
cool
now you can also perform slicing
operation
suppose
i write str str1
i want everything that is present
between the zeroth index to
the fifth index
i'll run it
it gives me
h pytho so if you check
in string one
it will start counting from the zeroth
index and go up to
the fourth index and exclude the fifth
index
so in my string 1 if i start counting
from the 0th index so it is 0 1 2 3 and
4 so it will
print from p till o
and that's the result
okay
now you can also use some inbuilt
functions with string
suppose i write str2
dot
find
so i want to find the index where my
m is in simply learn
so i'll
write m within quotations and print it
it returns me 2
if you check again
so s is at 0th index 1 is at the first
index and m is present at the second
index
ok
moving ahead
let's explore a few sequence data types
so we'll start with
list data type
ok
now
first of all let me go ahead and
declare a variable called split 1
equal to
and this will have some
text let's say this
is
orange
then
i'm going to create another variable
called l1
equal to
i am going to
my variable or my
string that is split 1
using the split function
and i'm going to split using the comma
so you can see here my string has comma
i'm going to separate each of these
words with a comma
and let's print l1
if i run this you can see it here
initially my split 1 was of type string
and now we have converted
split 1 to a list you can see this this
is a list and it is present inside
square brackets to verify
you can use the type function so i'll
write type of
split one
it should return string you can see it
here str
and now if i write
type of l1
it gives me a list
okay
now let's see a few more examples i'll
create another list called
list1
and let's see it has some values
the alphabet a
we have
the number one which is in terms of
string again because i have passed in in
quotes
let's say i have india
let's make it consistent with single
quotations
and
let me
print what is inside list1
if i run it i get my list
now you can check the data type
if i write type of list one it gives me
it is a type
list
now you can also perform certain
operations on list suppose you want to
add a few elements to your original list
for that i'm going to create another
variable called list 2
and let's say list2 has some values
let's say b comma
2. now
if i write
list 1
plus
equal to
list 2
and let me go ahead and
list one
let's see the result
there you go so our initial list had
three elements a1 and india and now we
have merged or concatenated two more
elements b and two and hence this
becomes our final list
okay
now moving ahead
let's see
one more sequence data type that is
tuple or tuple
now list and tuples we have already
covered in our previous video on
introduction to python if you need to
brush up what list and tuples are you
can check the previous video
so i'm going to create a tuple that is
top1 and i am going to
store some values
tuple you can create using braces
i have some value let's say a
b
c
d
and let's say e
or let's just restrict it to d
now you can check the type of tup1
you can see here dup1 is of type tuple
now
i'll create another tuple let's say tup2
and
it has some values let's say e
f
and let's say g
now
if i
write
dup1
plus
equal to dup2
and if i print
my tup1
i get the result
of a merged
tuple
which has values of both top1 and tup2
you can see here our original tuple had
abcd and then we merged the second tuple
and it has
and it has given us efg as well and
hence this becomes the final tuple
you can also perform some basic
operations on tuple let's say i'll write
dup1 multiplied by 2.
you can see the result here
it has printed
my original tuple twice
okay
now moving ahead
let's see our mapping data type
that is dictionary
again dictionary is also covered
in our previous
introduction to python video
you can also have a look at that video
now the way to declare a dictionary
is
i'll create a variable
dict 1
and dictionaries are
written using curly braces
and have key value peers
so i'll write my first key as one and
let's see
this dictionary is about animals
and i have let's say lion
as my first animal in the dictionary
then i'll create my second key
let's see the second animal i have is
tiger
and let's see
my third element
is
a dog
let me run it
and print
my dictionary
you can see this
we have the dictionary printed
now if you want to check the type you
can write type of
dict 1
it returns us dict which means
dictionary
you can also print the length of
dict 1
and it gives us 3 which means our
dictionary has 3 elements
ok
now moving ahead
we'll explore
our set data type
now as we understood that sets are
unordered collections of
values
and these values are always unique
so i'll write set one
let me give a space
equal to
again sets are written within curly
braces
i'll create a set
let's say it has some duplicate entries
as well
and i'll print my set one
it returns only the unique values so it
has dropped
this 5 which was duplicated
you can check the type of set 1
it gives us it is of type or the object
is of type set
now
suppose
i have
another set called set 2
which has values let's say
a
comma
b
and let's say we have some numbers three
and four
i'll tell you the operation that i'm
going to do
i'm actually going to
do an or operation
so i'm going to print
set 1
or
set
2
so this is an or operator in python
let's print the results you can see here
it has printed
all the values that are present inside
set 1 or set 2.
so in set 1 we have 1 2 3 4 and 5
and in set 2 we have a and b
so it has dropped 3 and 4 because these
are not unique and
3 and 4 are also present in set 1.
suppose i were to perform an and
operation
i'll write set1
ampersand
set 2.
if i run this
you can see here it has only printed
the unique values that are present in
both set one and set two so three and
four are the unique values and hence it
has printed three and four
let's say
i'll write set one minus set two
let's see the results
it gives us only those values that are
present
in
set 1
and are not present in set 2 which is
this
let's see the result if i write set 2
minus set 1
so this will return the unique values
that are present in set 2 and are not
present in set 1.
so a and b are the unique values that
are present in set two hence it has
printed as a comma b
okay
now
another data type we had discussed was
range
so range is basically a function if i
write x equal to
range
4
and i'll print x
it gives us from 0 till 4 because in
python the first index starts from 0 and
goes
till 4 so the range is from 0 to 4.
now you can also print the type of x
it returns us a range
now we'll see
some binary data types
binary data types are not very often
used in python but it is better if you
know
binary data types can be written as x
equal to
b let's say i have a string
i'll write within double quotations
hello world
and let me go ahead and
my variable x
you see here
we have hello world
and now
let's print the type of x
you see here this is a binary type which
is bytes
i'll show you another operation let's
say you want to extract a specific
value
from a particular index
from this
binary data
so again you can use the
indexing operation
suppose i write print
i want to extract the value present at
the fourth index
it gives me one one one now this is very
interesting
let's
deep dive into this
let's check
what is present at the fourth index of
my string
so h is present at the zeroth index
e is at the first index
l is at the second index the second l is
at the third index and we have o
at the fourth index
so
when we are trying to print the index
position it is actually returning us the
ascii value of small o
now here i have a
doc open which is from ibm documentation
if you see
the
ascii value of small o or lowercase o
you will find
that the ascii value is one one one and
hence it has written us one one one
let's try for
another
index number let's say i want to find
the value which is present at index
number
minus
2
and if i run it
it gives me 108
so minus 2 means it will start from the
last index
so minus 1 is d and minus 2 is l
let's see what is the ascii value of l
if you see it here the ascii value of l
is 108
and hence it has written as 108. so this
is how
the binary data types work in python
now let's convert some
sequence objects to other type of
objects let's say i have a string
called s which has
something like
messy is from
argentina
now you can check
the type of s
fair enough it tells us that messi is
from argentina is of type string
now
what i'm going to do is i'll use my list
function
and pass in my variable that is s so
that it converts s to a list
and let me go ahead and print my l
you can see here
my string s has now been converted into
a list
and this is the result
see here these are all
list elements present inside square
brackets
now if you want you can check the type
of file
it should return us
list
and you can see it here
now suppose
i have
another list let's say l1 which has
some
numbers let's say
one 15
3
6
0
8 4 and 3
let's see we also have one
okay so this is a list you can check
type of l1 fair enough it tells us that
this is a list
now i want to convert this list l1 to a
set
now as we know that set only contains
unordered unique elements
so if i write s equal to
i'll use the set function and then i'll
pass in my list variable that is l1
and let's print s
it only returns me the unique values
present in the list so it has dropped
the
duplicate elements such as
three and one
now you can check the type
of s it gives us set
okay
so that brings us to the end of this
demo session on
data types in python let me go to the
top and
i'll brief you what we did in this demo
so first we looked at
the different numeric data types so we
saw integer data type then we saw
floating data type
we also had
complex data types
we saw how to extract a real part in
imaginary part from a complex number
then we used
some type conversion functions to
convert the numeric data types from one
data type to another so here we
converted a floating type data to an
integer type data
similarly
we saw how to use boolean data types
then we saw about string data types we
also performed some basic operations of
using
indexing method to extract
different values
we also saw how you can use slicing to
extract a range of values from your
string we use the find function to find
the index of a particular
character in the string
then we learnt the important
sequence data types like list
then we had
tuples
and then we learned about
mapping data types such as dictionary
we also looked at set data type
now
later on we explored about
range data type and we looked at binary
data types we saw how
binary data type returns ascii value of
a certain character
finally we converted
strings to list and then we saw how to
convert
list to sets
first we will learn different number
data types in python then we will learn
type conversion between number data
types and after that we will understand
how to represent binary hexadecimal and
octal numbers in python and then we will
understand different number functions in
python
a programming language needs to have
support for numbers to carry out
calculations in python the numbers are
categorized into different data types
types are implemented in python as
classes
there are three numeric types in python
int for integers float for decimal
numbers and complex for complex numbers
let's explore these data types in
jupyter notebook
i have opened my jupyter notebook and
now let's see different data types in
jupyter notebook
for example first we'll assign a number
to a variable
num variable equal to 7
and now we'll check the type of this num
variable for that we'll write the
command type
round brackets num round bracket close
and then we'll run this command
we will get int as the data type
now we will assign a decimal number to
the num variable that would be num equal
to 7.7
and now
we will check the type of the num
variable and
run this command
what we get is the float float as the
data type for the num variable
now we will assign a complex number to
the num variable
and we will check the type for this num
variable
and run the command we will get the
complex data type as the result
now if you want to get the real part of
this complex number
you just have to write the command num
dot real
and just execute the command you will
get 6.0
as the real part of this complex number
here you can see you just quote the
number in float data type
the complex number in python are stored
in flow data types whether it's the real
part or it's the imaginary part now
we'll see the imaginary part
num dot image
and now you will run this command you
will get 7.0
here also you can see that the imaginary
part is also stored as float
in python for complex number
now we will perform different arithmetic
operations with these data types
first we'll mention
arithmetic operations
now we will assign numbers to the
variables and perform different
arithmetic operations for that we will
assign
17 as a number to the variable num1
num1 equal to 17
and
the second variable num2 we will assign
the number 25
and now we will perform
different arithmetic operations first
we'll start with addition
so write the simple command that would
num1 plus
num2 and just run that command
you can see the result as 42. it's as
simple as that in python you just have
to write print and in round brackets
just write the operation you wanna
execute
now we will see the subtraction part
we'll write print
num2 minus
num1
and execute this command and we'll get
the result as 8.
now we see multiplication
num1
into
num2
and execute this command and we'll get
the result as 425
now we will divide
num2
divided by
num1
and execute this command
and we'll get 1.47
here you can see as we have assigned int
values to the num1 and num2 variable we
got the result for addition subtraction
and multiplication as in data type only
but for division we got it
as float
this is because python always gives the
output for division in decimal numbers
only
just to have minimum accuracy loss so
if you want to just get the output of
the division
as an end value you just have to perform
this
num2
and two slash signs and then num1 and
then execute the command
you will get one as the output so to
just get into the output of the division
you can use two slashes
next command we'll see is to raise a
number
to another number
so to just get 2 to the power 4 we will
write the command print
2
2 asterix symbols
and
4.
and just execute this command you will
get the output as 16
we got 2 to the power of 4
by just using two aztec symbols now to
get the remainder of the division
we just have to use the modulus symbol
so for that
4
modulus
2 and just execute the command
you will get 0 as the remainder
you can perform the same operations on
float numbers and complex numbers
now we will see
an arithmetic operation on complex
number
so we will assign a complex number to
variable
that would be g
equal to 1
plus
5 j
and another variable we will assign the
value 2
plus
3 j
and we will assign the operation
i equal to
g
slash h that is the reason
and
print the output
and will execute the command
we will get the following result for the
division of two complex numbers
now we will see type conversions in
python for that we will move
there are mainly two types of
conversions between numbers in python
first is using arithmetic operations
that is implicit type conversion and
second is using built-in functions that
is explicit type conversion
let's understand the concept of
conversion with the help of jupiter
notebook
so here
we will write first convergence
first we will assign a number
to a variable that would be a equal to
196
and we have seen in the previous
examples that its type is int
now if we put this number in two double
quotes
and now we'll check its type
that would be type
a
and run the command we'll get it as
string
so in python when we just put a number
in double quotes it will see it as a
string
and to get this number as an int
we just have to use explicit type
conversion for that we will write
b
equal to
int
a
and now we will check its type
type b
and run the command
we will get into
the data type for the b variable
the a variable is still the string data
type
and b variable has now turned as int
data type
and now
to turn a as a flow data type we can
write
c
equal to
float
a
and check its type
type
c
and run the command and here we can see
that it has turned into the float data
type
so a is still the string data type but c
has been converted the a variable into
the float data type
we can also convert the a string data
type into complex data type
just
we have to write t equal to
complex
and in brackets we have to write a
and we can check its type
and we can
the t complex number and we have just
execute the command
and we can see
that the complex number is 196 plus 0j
and we can also check its type
by just
writing print
type d
and we will run the command and we can
see that the class is complex
for the variable d we can define the
complex data type by different methods
one of the method is
we just have to write print
complex
and in round brackets we just have to
assign both real and the imaginary
numbers that would be 3 comma 6
and just execute the command
and here we got a complex number that is
3 plus 6 j
now we have seen the explicit type
convergence
now we will see some implicit type
convergence that is using arithmetic
operations for that we will assign
a float number that would be 2.6
to a variable
equal to 2.6
and
b equal to
6
and we will assign an arithmetic
operation that would be
c equal to a plus b
and
print the output
and execute the command
by using just arithmetic operations we
have seen that the addition of a float
number and the integer number turns out
to be a float number
so now we have seen the implicit type
conversion example
now we will see the representation of
binary hexadecimal and octal numbers in
python
all the integer numbers can be
represented as binary hexadecimal and
octa
to represent it as binary in python we
have to prefix it by using 0 small b or
0 capital b and for octal
we can prefix it by using 0
small o or 0 capital o
and for hexadecimal we can use 0 x or 0
capital x let's see this representation
in jupiter notebook
first we will write representation of
binary hexadecimal and octal numbers
now
we will first see
binary to decimal conversion
for that
we will first write
0
b
1 1 0
1 1 0 0 0
and then we'll just run it
and see 216 as the decimal conversion of
this binary number
now we'll see the same for the octal
for that we'll write 0
small o
12
and just run this command
and we can see that it has turned 10
in the decimal number system
for hexadecimal we will write
0
small x
and 12
and just run the command
and we can see 18 as the decimal
conversion of the hexadecimal number
system
we can also use 0 capital x
12 and just on the command
we'll see 18 the same output as of 0
small x 12.
let's see some operations with fractions
for that first we will comment fractions
now we will import the fraction module
for that we'll write from
fractions
import
fraction
s
f and first i will
execute the addition operation for
fractions for that will write print
f
1 comma 3
just for the fraction numerator would be
1 and the denominator would be 3
now we'll write the operation addition
and f
the second fraction that would be
okay we will write the same only one
comma three
and on execution of the command we will
get two by three as the output
we can also perform different operations
okay we will
just see the reciprocal of the fraction
for that we will write print
one
upon
f
five comma six
and just run the command
here we can see the reciprocal function
that would turn out to be six by five
now we will explore different number
functions
first one that we would explore would be
absolute
absolute function would turn any
negative number into the positive number
for that
we will just assign a number that would
be x equal to minus
9.8
and
we will just apply the absolute function
abs on the variable x
and just run the command
here we can see that has turned x equal
to minus 9.8 to 9.8
now
we will see some different functions for
that we will import the math
module
import
math
and we have different values stored in
the math module for example pi
we'll print the pi value print
math dot pi
and run the command
here we can see the value of the pi
3.1415926535893
we also have exponential value in math
module
for that we will write the command print
math dot e and execute the command
here we will get the value
2.718281828459045
for the value of e in the math module
now we will also see
exponential to the power 10
for that we will write the command print
math dot
exp
round brackets
10
and execute the command
we will get the value 22026.465
we can also perform log operations
for that we will write the command
print and we will get the log of 1000 to
the base of 10.
for that we'll write
math
dot
log
to the base 10
the would be
1000 and we will execute the command and
we will get 3.0
you can also get the factorial by the
math module
all right print
math
dot factorial
factorial of
6
and we'll execute the command and we
quote the factorial of 6
that is 720
now if we want the square root of a
number we will write the command
math dot
sqrt
and in round brackets we will write the
number for which we need the square root
we will write 25 and execute the command
and we will get 5.0
this square root number gives the float
number as its output
and we can also find out the maximum
numbers from a bunch of numbers for that
we have to write the command
max
round brackets
and the bunch of numbers from which you
want the maximum value
like 1 comma 33 comma 55 comma
7 comma 99 and just execute the command
you will get the maximum number that
would be 99 and if you want the minimum
number
you can write the command min
and in round brackets just write the
bunch of numbers
1 comma 3 comma 66 comma 88 comma
seven
and just execute the command
you will get the minimum number that
would be one
now you'll see the ceiling function for
that we'll write the command
math
dot c
and in round brackets we'll write the
number for which we want to use the same
function minus
43.5
and execute the command
you will get minus 43
so what the scenic function does is
it would give the highest value or the
greatest value for the number we have
entered in the ceiling function
now we will see the floor function for
that we'll write the command
bracket math dot floor
and we'll write the number for which we
want to use the floor function
minus
43.5
and execute the command
we will get minus 44.
so the floor function will give the
output value
just
below the or just the lowest value
of the value entered by us in the floor
function
now we'll see the power function for
that we'll write the command print
math dot pow and in round brackets
will write the number
2
and the power which we want that would
be 6
and just execute the command
here we can see
that 2 to the power 6 we have got the
output value as 64.
now we'll see some trigonometric
functions
first we'll see cos of x
like python number method cos returns
the cosine of x radians for that we will
write the command
math dot
cos of 0
and just run the command it will give 1
as the output
so
this method returns a numeric value
between -1 and 1 like which represents
the cosine of the angle
we will see another example for course
for that we'll write
math dot cos
and in brackets we'll write the angle
math
dot pi
and we'll execute the command
and we'll get the output as -1
now we'll see 10 trigonometric function
so the python method 10 it returns the
tangent of x radians
for that we will write the command
math.10
of angle 0
and we will execute the command
we will get 0 as output this method
returns a numeric value between -1 and 1
which represents the tangent of the
perimeter x
we will also see another example for tan
we'll write
math dot
10
math
dot
pi by
4 and execute the command
it gives us
0.999999 that turns out to be 1.
now we will explore some random number
functions for that we will write the
command
import
random
and import the random module
now we'll see the first function that
would be rand range for that we'll write
the command print
random dot
rent range and in circular brackets we
will write the range from which we want
the random number
that would be 10 comma 20 and execute
the command here we go 12 as the random
number
now we will define a list that would be
x
equal to
square brackets
one
two
three
four
and five
now we'll see another function
that would be choice and it would give
any random number from string
list or tuple
so for that we'll write the command
random dot
choice and in circular brackets we'll
write
or we will pass any list string or tuple
here we will pass this list
x and execute this command
we will get the random number three so
we are going to talk about object types
in python then we will see the different
type conversion functions that are
available in python
then we see the different types of type
conversion
all right
now let's look at the different types of
objects in python
so we have less
you have tuples numbers strings
dictionaries sets you even have file
objects
then you can see we also have other code
types such as boolean and none
then we have
program unit types like functions
modules and classes
now we will touch upon most of them in
the demo section of this tutorial then
we also have implemented related types
all right
now let's see how you can convert one
data type to another using type
conversion
so python provides two types of data
conversion techniques one is called the
implicit type conversion and the other
is called the explicit type conversion
now in implicit data type conversion
python can automatically
convert one data type to another data
type this process does not need any user
involvement
while in external conversions
users
convert the data type of an object to
required data type by using predefined
functions that are listed here so you
can see here we have the different
functions so if you want to convert a
specific value to an integer you can use
the int function we have the float
function
now we have something called as ord so
the ord function
accepts a string of unit length as an
argument and returns the unicode
equivalence of the past argument now we
also have
hex and oct so
the hex function
is used to convert an integer number to
its corresponding hexadecimal value
similarly the oct function will convert
the corresponding
or let's say we'll convert an integer
number to its corresponding octa decimal
value
we have tuple list set dictionary str is
for string you can convert a number into
a complex number by providing its real
and imaginary part
we also have this chr or the character
function
now this is how the basic general syntax
looks like you have the required data
type followed by the expression
okay
so let's head over to our jupyter
notebook and learn the different types
of objects as well as
look at the type conversions in python
okay so here i am on my
jupyter notebook let's first
look at
number objects so i'm giving a
comment
as number objects
all right let's see i have a variable
called num
which is equal to let's say 2
now
it's very simple that 2 is an integer
so if you want to check the type
you can just use the type function and
it gives us int which means integer so
here 2 is of
a type called number object
let's say you want to pass a floating
value
that's a 2.0
see the results
2.0 is of type float and again
2.0 or 2.0
is a number object
now you can perform various operations
on number objects suppose you want to
add a few numbers
so let's say 321 plus
365
and i'll say add
it gives us the addition of these two
numbers which is 686.
now let's say
you want to
perform a multiplication operation
let's say 62 multiplied by 2.5
if i hit shift enter it gives me the
multiplication of the product of these
two numbers that is
55.0
now
python by default will
convert the result to a floating point
number if there is one integer and this
one float
if you want to return the exponent of a
number let's say i want to know 2 raised
to the power 4
so i'm using double asterisks to
represent the exponent operator
if i hit shift enter it gives us 16. so
it's basically
two multiplied four times
now you can also
import specific libraries so let's say i
want to import the math library
and i want to print
the value of pi so here i have written
import math and then
using the module math i am
trying to find the value of pi let's run
it you see here it says 3.141 so on and
so forth
now you can also
import the random module let's say i'll
write
import random
and then
let's say i want to print a random
number
you can use the random dot
random function let's run it
you see here this is a
random value that
python has generated if i run it again
this value changes let's run it again
again this value changes
okay
now we'll shift our focus to
understanding string objects in python
so i'll give a comment string objects
let's say i have a string
a is equal to and let's say the string
has india
okay
now if you want you can print a it says
india
now suppose i want to
extract
the value that is present at the zeroth
index of the string so the way to do is
i'll pass in my
variable name that is a and within
square brackets i'll give the index
value that is 0. now one thing to
remember in python the index value
starts with 0 and not 1. so if i do
a of 0 it gives me i because i is
present at the 0th index
now let's say i want
the last value
in this string india so i need to return
a for that i can use negative indexing
by using minus 1
if i do minus
1 it gives me
a which is the
element present at the last index
now let's say
i'll write a
1 and colon
let's run it
you see the result here it says ndia
which means python has returned
everything starting from the
first index
till the last index
so here colon means you need to return
everything that comes after the first
index
now
let's see
i'll write
a
and i'll add
let's say xyz
run it
you see here
this xyz has been concatenated with the
value that was present inside a that is
india so the result is india followed by
xyz
okay now
if i write a multiplied by
7
it will print
india 7 times without a space
you can see it here
cool
now let's say you want to replace
certain values
in the string you can use the replace
function so if i write a dot replace
let's say i want to replace ia
that is present in india
with let's say
xyz
let's run it
you see here
ind is fine after that we have ia and
that ia has been replaced by xyz
now let's move on and understand
list objects in python so i'll write
list objects
okay
so let's go ahead and declare a list l1
within square brackets
let's say we have
values like 101
let's say
america
and then let's say we have another
floating value let's say 2.05
this is my list if you want to print the
list you can use
l1 to print it you see here this is my
list l1
now if you want to find the
length of l1 you can use the len
function
if i run it
you get 3 which means there are 3
elements in the list 101 america and
2.05
now if you want to extract certain
values from the list for that you can
use the indexing method let's say i'll
write
l1 of
1
that gives me america because
at index position 1 we have america so
101 is at the 0th index america is at
the first index and 2.05 is at the
second index
next
let's say i write
l1
and then
i give colon -1 let's print it so that
gives me
101 in america so what it does is
this colon minus 1 will exclude the last
index and print the other two
elements in the list
okay
now if you want to
append
some elements to the list you can use
the append method so i write l1 dot
append
within brackets i'll give my value let's
say
usa
now let's go ahead and print l1
if i run it you can see the difference
earlier
my list had three elements 101 america
and 2.05 now we have added the fourth
element that is usa
cool
now you can also use the
pop function in
python let's see what it does
so i write l1 dot pop and i'll give
let's say three
if i run it it returns me
usa because usa is present at the
third index of my list
if i write pop one
it gives me america because
america is present at the first index
all right
now you can also
reverse the elements in a list if i
write l1 dot
reverse function
if i run this and then i'll
print l1
you see the result here we have 2.05 and
101 which is printed in reverse order
the reason being
we have already popped america and usa
out and we are only left with 101 and
205 and if you reverse
the current list
it will be printed as follows so 2.05
comes
at the beginning and then we have
101.
let me just
rerun my list again to show you the
difference
i have run my l1
let's run this append query
and now
let's use the
reverse function there you go
so now our original list has been
reversed so you have us at the beginning
and 101 towards the end
okay
now moving ahead let's see
the next type of object in python that
is dictionaries
okay
let's see i'll create a dictionary
called dict 1
and you might be aware that dictionaries
are created using the curly braces
so i'll have my
key value pairs let's say my key is 1
and the value it holds is let's say
the names of animals
tiger
comma we'll have the second key and that
second key will have the value let's say
lion
and let's see
we have another element with the third
key
and let's see
we have mouse
okay
now
let's print our dictionary
so this is how my dictionary looks like
now
you can
display the keys
by using the keys function
so this will return all the keys present
in the dictionary you see here 1 2 and 3
are my keys
similarly
you can display the values in the
dictionary
you need to change this keys to values
if i run it you see here
tiger lion and mouse are the
three values
now suppose you want to add another
element to your dictionary for that you
can write
dict 1
and give the
fourth key equal to
the value let's say cat
now let's run
dict 1 and see the difference
there you go so here we have added
another element to the dictionary which
is cat
now moving ahead
let's explore
double objects
okay so we'll create a tuple called t1
equal to
we'll have the values 1 comma 2 comma 3
comma 4
and let's say you want to print the
length of tuple t1 it gives you 4
because we have 4 elements in the tuple
t1
now let's say i'll declare
one more tuple called t2 and this time
we'll have two more elements in the
tuple so i'll write t1 plus
followed by the two elements that i want
let's say 7 comma 9
and i'll print t2
if i run it
you can see here we have added 7 and 9
to our original tuple that had 1 comma 2
comma 3 comma 4.
now you can also use the indexing method
or the slicing
technique to extract values from the
tuple let's say i write
t2 of 3 it will return the third element
that is present in tuple
d2 so if you see here
my
third index has the element 4 hence it
has returned four
cool
now moving ahead
let's see
how file objects work in python
all right now
using python you can create
files
let's say i want to create a text file
in python using the jupyter notebook for
that i can write f1 equal
to i'll use a function called open
and inside this open function i want to
create a text file and first
i'll write something into that file
let me show you so this is a folder that
i have
the folder name is called object types
and it is present in my desktop so i'll
use this location
and here you can see now this folder
contains no files as of now but we are
going to create text file using python
let's see how to do it
so here i'll paste my
location that i just copied
now one thing to note is you need to
convert everything to
forward
slash or you can use
double backslash also
i'll give
another forward slash
and let's say i want to
create a file in the name of data.txt so
it is going to be a text file
make sure everything is
inside single quotation
and i want to open the file in
write mode so i'll write w here let's
run it and see the difference
now if we check our folder
you see here earlier there was no data
file now we have created a text file in
the name of data you see here there are
no
information or data inside this text
file next we are going to add some data
to this text file
let's
go back to our jupyter notebook
okay
so we'll write some data to that file so
i'll write f1 dot
after that i'll use the write function
and within single quotations i'll write
let's say hello
simply learn
and then
i'll give backslash n to go to the next
line
i'll write again f1.write
and i'll pass in another message let's
say welcome to
python programming
and we'll give another backslash
followed by n
and then finally we'll close the file so
i'll write f1 dot
close function
let's run this
and we'll see the difference now
if i open this the yuko
we have some data in this
text file that is hello simply learn
welcome to python programming
so this is how file objects work in
python
all right
now moving ahead we'll see
how
sets work in python
suppose i create a set called s
and i'll use the set function
and i'll pass in
india
so this is a string
and i want to convert the string to a
set
let's say i have
another set called s1
and here i have
a list of values let's say u
s
and let's say a
now if i write
s comma
s1
so what set does is
it will return only the unique values
that are present inside each set so here
if you see
india
all the elements are unique except i
because i is repeated twice so it will
return i only once in the result but usa
has all the elements present only once
so
set will return all the elements
now what if i'll
write let's say s
ampersand
s1
so
this will give me only the
common element that is present in both
the sets so if you see here in india and
in u s and a
only a is repeating in both the sets so
it gives me a
suppose i write
s
this is the or operator and i'll write
s1
if i run it it gives me
all the elements that are present inside
set s and s1
excluding the repeating elements so here
i is repeating so it has printed only
once
similarly you can write
s minus s1
so you get
only
those elements that are present inside
set s and are not present in set s1
now in set s e is present as well as is
present in set s1 so it has excluded e
from the result
okay
now we'll see some operations let's say
i'll write equal to 7
and be equal to let's say 2.0
i'll
add a and b and store the result in
my variable r which stands for result
let's see
the output if i write print r
it gives me
9.0
and if i check
type of r it gives me
there's a spelling mistake i'll write
type of r it gives me float so here
python is performing
implicit
type conversion so if you add an integer
with a floating point number the result
will be a floating point number and not
an integer
now if you
say equal to 7
and let's say b equal to same 2.0
and this time i am explicitly defining
my result to be an integer so i am using
an integer function so if i write a
plus
b
and if i print r
you see the result it has given me an
integer which is
9.
now to verify you can also use
type of r
it gives me integer but earlier
it returned us float
so this is how
implicit
and explicit conversion
work in python
now this example was for numbers
similarly you can
also
perform for strings
and for less tuples and sets
moving ahead
one thing i wanted to tell you was you
cannot add a string
and an integer
suppose
i'll give a comment
string
and integer addition
suppose i have a variable called a which
has a value of a 7 so 7 is an integer
here then i have a variable called p
which has a value 2 but this time i'll
assign this to within
quotes so this becomes
of type string
now if you want you can check that as
well if i write type of 2
rather type of b it will give us str
which means string
now let's see
i'll write r which stands for result
equal to
a plus b
now if i print r
it will give us an error because you
cannot add a string with an
integer
so it says unsupported operand
the way to fix this is you need to
convert this string into an integer
explicitly
so this time we'll say equal to 7
b
equal to
2 so
it is a string
now i'll write
r equal to
a
plus
i'm going to use the integer function or
the int function to convert my b to an
integer
and then i'll print r again let's do
this there you go so here we have
converted my string value to
a numeric value
of 2 and this time it works fine so 7
plus 2 is 9
okay
now let's see how you can convert a
float value or a floating number into an
integer number let's say i have a
variable called a which has a value
let's say 77.9
and i'm going to create another variable
called int underscore a
and i'll pass this to my integer
function
so it has int of a
now let's print
int underscore a
so you have 77 so
my integer function has truncated the
decimal point value that had 0.9
if you want to check the type you can
use
the type function i'll write type of
hint underscore a
so it gives us integer
now you can also convert an integer to a
floating point value
so if i have a variable called a that
has a value of let's say
50
and if i write float underscore e equal
to i'll use the float function to
convert the
variable e to a floating point value
and let's
print float underscore a
so it gives us 50 50.0 instead of 50.
you can also check the type
of float a
it gives you float
okay
now you can also convert an integer to a
complex number
let's say i'll take the same value equal
to 50 i'll write comp underscore e which
stands for complex a
i'll use the complex function
and pass in my
variable that is
e
now let's
comp underscore a
so it gives us
50.0 j so 50 is the real part and 0 j is
the imaginary part
you can also convert an
integer to a string
i'll take the same value let's say 50
i'll write str underscore a equal to
str of a so i'm using the string
function to convert my integer to a
string
let's print str underscore a
it should be an underscore and not an
hyphen
let's run it there you go you have 50
within single quotes
you can also check the type of
a htr underscore a it gives you string
cool
now
we learn how to convert a string to a
tuple
so let's say i have a string that has
india as its value
if i write
ts equal to
i'll use the tuple function and pass in
my variable that is s
and then we'll print ts
you can see here
python has converted my string s which
had india into a tuple of individual
elements
and my tuple is present inside brackets
cool
now similarly you can convert a string
to a list
i'll use the same string as equal to
india
and then let's say i want to convert it
to a list i'll use l1 equal to
followed by the list function and inside
the list function i'll pass in my
variable that is s
and let's print l1 and see the
difference
you see here
my string has now been converted into a
list you can also check the data type of
l1 or the object type of l1
it returns you list
similarly you can also check the type of
ts
it gives you tuple because we converted
that
string to a tuple
now let's explore how you can convert a
tuple to a list let's say you have a
tuple called t
and it has a list of names let's say
john
we have mary
then we have let's say mark
now to convert into a list we'll use the
list function again let's say
l2
equal to list of
t
and let's print l2
so this is a list because it is present
inside
square brackets
you can check the type of
t
so t is a tuple you see here
if i change this to l2
it gives you list
cool
now
moving to the next section where we'll
see how to convert
integer to binary
suppose i have a variable called a equal
to
10
and then
i have p equal to
bin of
let's say we have another variable which
is c
and here i want to convert my integer
into a
hexadecimal value or a
octa decimal value for that you can
write d equal to use the oct function
for
octa decimal value
okay
now we are going to print them one by
one
so i'll write print off b
print of
c
and then we'll print what is there
inside d
we'll run it and you can see the results
here
so binary of 10 you see here
hexadecimal of 10 you see the value here
this is an extra decimal value
then we have the octa decimal value of a
okay
now moving to the
final section of this demo
you can convert a number to its
corresponding
ascii character
let me show you how to do it
suppose
i have
n1 equal to
76
now if i write
chr
of
n1 and run it it gives me l
now let's see our ascii table so this is
my ascii table and
for 76 you can see here the character is
l
so this
chr of n1 will return
the corresponding ascii character for
that particular number so here 76
belongs to l
let's say we have another number n2
equal to let's say 100.
now if i write chr of
n2
and run it it gives me
lowercase d
we'll see the table again
and if you see for 100 we have lowercase
d
now here you have a list of characters
these are special characters you have
uppercase characters you have add the
rate you have numbers each of them have
their own ascii values
cool
now
you can
convert string character into unicode
values now let me tell you what unicode
value is so computers on a basic level
deal with numbers so letters that appear
on computers are stored by computers as
a list of numbers
so the unicode standard provides a
unique number for every character and
supports multiple languages and all
special characters
so let's say i have a string s which has
the value of capital a or uppercase a
if i write r which stands for result
equal to
ord so this is the function which
converts a string to a unicode value
i'll write ord of s and will print r
if i run it it gives me 65
so
65 is the unicode value of a
now you can also have digits let's say i
have 7
i'll run it
so 55 is the unicode value of string 7
let's try for any other letter let's see
v
and run it you have 86
okay
so we'll understand what is a string in
python
and how to create strings in python
then we look at the different string
methods and how to perform string
indexing
and
all these will see with the help of
hands-on demonstrations on the jupyter
notebook
so let's understand what is a string
so a string in python is an object that
represents a sequence of characters
in python we have str as the data type
of string
now you can create strings
using single quotes or double quotes so
here is an example
where we have used a single quote to
write a string so our string is hello
india which is inside a single quote
below if you see we have the same string
written within double quotes so these
are the two methods in which you can
create strings in python
now you can also use triple quotes which
are generally for
multi-line strings or dot strings so
here is an example we have a string
called str3
and
the content it has is human psychology
is an interesting subject now if you
print the string it will be printed in
two lines and not in a single line
now we'll be exploring much more in
detail in our demo session so please
wait for a while next
we have string indexing so if you want
to extract a few characters from your
string you can use the indexing method
so in python
a string starts with the
index number zero
so here we have a string which is
healthy
and
the first element is present at the
zeroth index so at the bottom you see
the forward index on the top we have the
reverse index or the negative indexes
so in python as i said the first index
is at the zeroth position so h is at
zero e is at the first index a is at the
second index so on and so forth now
similarly if you look at negative
indexing it starts with minus 1 in
reverse order so we have minus 1
for y minus 2 for h minus 3 for t and so
on and so forth
now let's head over to our jupyter
notebook where we'll
learn about strings in python in detail
okay so i'm on my jupyter notebook first
i'll create a
new notebook i'll click on new and then
select python 3
ok
so here let me
rename my notebook as
strings in
python demo
i'll click on rename
okay
now let's start with our first example
i'll create a variable called str1 that
will have a string
you can see here i am using single
quotes now i'll write hi
sam
so here
str1 is holding a string called hi sam
and let's go ahead and print the string
str1
i'll hit shift enter to run it you see
here i have my string printed hi sam
if you want to check the
data type
that str1 holds
you can use the type function and inside
the type function i'll pass in my
variable str1
if i run it you see here it gives us str
which means
it is of type string
now let's create another string str2
using double quotes this time so i'll
write let's say
hello
angela
i can give exclamation mark
okay now let's just print the
second string you see here this is my
second string which is hello angela if
you want you can also use the print
function here
and run it you get hello angela
now let's write a multi-line string
using triple quotes so i'll write str3
equal to
i'll use triple quotes
and then
i'll say
hi everyone
go to the next line i'll write today
we will
learn
about
i'll go to the next line and i'll write
strings in python
then i'll again give triple quotes to
close my string
and let's just print this str3
if i run it you can see it here i have
now written a multiline string hi
everyone today we will learn about
strings in python let me just add a s
there you go
okay
now coming to the next topic we'll learn
about indexing
all right
let me declare a string str1
which has
value as simply loan
now
to use indexing and extract certain
items in a string or values in a string
you can use square brackets and inside
the square brackets you can give the
index position
for example if i write str1
and in the square bracket i'll give
let's say
i want to
find the element or the value present at
the zeroth index
let's run it it gives me s
because as we learnt in the slides
the first index in a string
starts with the zeroth number
so i have s in my zeroth index so hence
it has printed s
let's explore a few more if i write str
one of let's say i want to know what is
present at the third index if i run it
it gives me p you can check now so s is
at the zeroth index i is at the first
index m is at the second index and p
is at the third index
let's say i'll write str str1 of
let's say 12
we can see the difference now it gives
us an error it says string index out of
range the reason being simply learn
does not have any value at the twelfth
index so it's printing an error saying
string index out of range
now let's change this to
six and see what we have at the sixth
index we have l
if you count here s is at the
zeroth index i is at the first index m
is at the second index p is at the third
index
the first l is at the fourth index
again i is at the fifth index and then
we have the second l at the sixth index
so we have l printed here
now
let's see how to use
the slicing operator using colon
i'll write
slicing operator
okay
i'll use the same string as tr1 let me
print it once again we have simply
learned
suppose i write str1
within brackets i'll use the slicing
technique now i want everything starting
from the zeroth index
i get simply learn so here i am printing
everything that starts with the zeroth
index
next let's see
what we have
if i print my string str1
and write 1s to 6
i'll run it
it gives me impli so if you notice here
i want to extract whatever is present
from the first index
till the sixth index but excluding the
sixth index so in python
the indexing method or the slicing
method will exclude the last index so
here if you see
i is at the first index m is at the
second index p is at the third index
l is at the fourth index
and then we have i at the fifth index
and we have excluded the sixth index
that is the second l so hence it has
written us impli
now similarly let's see
we'll see another example i'll write
str1
this time i'll use colon
6.
if i run it you get
simply
so it has printed everything starting
from the zeroth index till
the sixth index but excluding the sixth
index so you have all these values
from zeroth index till the fifth index
okay
now you can also
reverse a string for that you can use
negative slicing using
two colons
if i write print
str1
and within square brackets i'll give
colon colon -1
let's run and see the result
there you go if you see this it has
printed my original string which is
simply learning reverse order now
so this is a very simple method if
someone asks you to reverse a string or
print something in reverse order you can
use the negative slicing method
now let's explore a few more example
if i write str1
and within brackets i'll give minus 1
and run it
it returns me n because in my original
string if i go on the top i have n at
the last index which is
here -1
similarly let's see what we have at
minus
3
we have a here if i go to the top
you see here
n is at minus 1 r is at minus 2 and a is
at minus 3 and hence it has given us a
now let's say i'll write str1
i want to print
minus 2
colon and let's see the result it has
given us
r and n
so here we are printing
only the
last two elements in the string hence we
have used -2
okay
now python does not allow you to
reassign values
in a declared string let me show you
what i mean
i'll give a comment here
reassign
strings
suppose
i have the same string str1 which is
simply learn
say i write str
and i want to replace
the value present at the third index
with let's say
o
and
if i were to print
str1 now
python will throw an error saying str
object does not support item assignment
so it is immutable
like tuples where you cannot reassign
any
values
you can also
delete a string
see i have another string called str2
which has a value of
let's say python programming
you can use the dl keyword
and write str2
and now let's print str2
you will see
that
it says name str2 is not defined because
we have already deleted str2
the above stuff
okay
now let's go ahead and see some of the
important
string operations
okay
see i have
str1
which has
python
now one thing to note i am using either
single quote or double quote you can use
whatever you want
let's say i have another string which
has programming
so these are my two strings
let's
perform a few operations on these
strings
see i write
str1
multiplied by 3
and i'll run it
you can see here it has printed python
thrice because i have said str1
multiplied by 3 so in str1 we have
python and multiplying 3 returns python
3 times
now let's see i'll write str1
plus
str1
it has merged python twice so i have
python and python repeated
let's say i write str1 plus str2
we see the result it gives us python
programming so basically
if you use
the plus operator with two strings
python will perform a concatenation
operation which means it will merge both
the strings
now if you want to find if a specific
character is present in a string or not
you can use the in operator for this
let's say i'll
print whether
w
is
present in
str
1
but run it it gives us false because in
str1 we have python and if you see here
we don't have the letter w in python and
hence it has given us false
let's
now let me copy this
i'll paste it here let's try whether o
is there in
string one or not it gives us true
because we have
an o here
you can see here we have an o
similarly
let's say
i want to find whether
l a
is there in string
2 or not
but run it it gives us false because in
string2 we have programming and we don't
have any la
present in programming
let's say we'll see whether r o is
present in
string two or not
this time it returns us true because if
you see here we have ro in programming
and hence it has given us
true
now you can also
print a raw string using the
r alphabet
so the way to write is i'll write r
give a
single quote let's say i'll give a
location
c drive
two forward slash and let's say i'll
write
python 3.7
and run it it gives me a raw string
now
let's see some formatting methods i'll
write
a comment saying
format methods
okay
i'll write a print statement
i'll give double quotes and here
let's see the first example where i'm
using
curly braces i'll write
and
i'll give another curly braces
you'll get to know what i'm doing once i
finish this
let's say i have a message
both are
best
friends
then i'm going to use my format
method
and inside this i'll pass in my two
values for these braces
so these curly braces will be replaced
by
the words that i
pass in or the values that i pass in
within the format method
so here i'll write let's say
james
and my second person would be
brad
now let me run it
you see here
what python does is it replaces
the curly braces with
the names that have passed within the
format method so it takes the first
argument for the first curly brace
and the second argument for the second
curly brace
so my statement becomes
james and brad
both are best friends
now let me just copy this i will show
you another example
this time i'll
give 1 and
0 inside the curly braces
now if i run this
there you go
so here
james is at the zeroth index so this is
basically a list where james is at the
zeroth index and brad is at the first
index so if i write 1 and 0 it will take
brad here
and then
for zero it will take james so now my
message becomes brad and james both are
best friends
now let's try out another example i'll
paste it here
i'll use
two variables let's say a and b
and inside my format method
i'll write a equal to james
and i'll assign b as brad
let's run it
there you go we have our message printed
james and brad both are best friends so
here a refers to james and b refers to
brad
cool let's explore another example
i have a variable called name and that
has a value
angela
and then i have another variable
it's a salary
of
100 000
i'll use a print statement
i'll print a message
her
name
is
i'll
use percentage
s for string
give
a backslash n for next line and i'll
write
her
salary
is
then i'll write
percentage d
this is for numbers
and then i'll give another percentage
and let's see i'll write
my two variables niemann's salary
let's
see what we have in the
result
i need to close my double quotes here
i'll exclude it from here let's run it
there you go so i have my message here
her name is angela her salary is
hundred thousand dollars
i'll just
delete this piece here we'll run it
again okay
now this percentage s
refers to the name
and we have declared her name is angela
so my first statement or the message
becomes her name is angela
and the next
message is her salary is percentage t so
percentage d here refers to the salary
where we have 100 000
so the next message is her salary is 100
000
so these are the very basic and
important
print methods or formats that you can
use
while working with strings
now we'll explore a few
functions that are readily available in
python to operate with strings
i'll take my same string str1 as simply
learn
and then
i'll create another variable called str2
i'll write str 1 dot i am going to use
the
capitalize
method
ok
let me make one correction i am going to
write everything in lower case so that
we can see the difference how
we can capitalize the string
so i'll write my print statement print
old value
this is going to my message
i'll give a colon
followed by my double quotes and i'll
pass in my variable str1
okay
now i'll copy this
in the next line we have
a new value as str 2.
let's run it and see the difference
there you go so here my old value has
simply learned in all
lower case but when i used the
capitalize method
so python has converted my first letter
and simply learned to
uppercase or capital keys
cool
now let me copy this
i'm going to use the same example
for
the next three methods
let me show you how the case fold method
works
this time i'm going to pass my input
string in all upper case i will write
simply learn in uppercase
and instead of capitalize i'll write
case fold
let's run it and see the difference
there you go
initially we had simply learn in
upper case and now we have converted
into case fold so
all the letters are in lower case
now moving ahead
you can also use the
upper method to convert a string into
upper case
let's say i have a string
where
few of the letters are in upper case and
few of the letters are in lower case
this time i am going to convert
everything into upper case so i'll use
the upper function instead of case fold
let's run and see the result there you
go so this time
python has converted my original string
into uppercase
and likewise you can also use the
lowercase
instead of upper if i write lower you
see here everything has been converted
to lower case
cool
okay
now i'll show you how the
title method works
so in title method all the words
basically the first letter of all the
words will be in upper case so suppose i
have
a string
which is
simply learn
company so i'll write
let's say
this is my string and i'll
i'll convert my str1 to title case
let me run it
so this is the difference you can see
the first letter of the first word is
upper case
again
the first letter of the second word is
also in upper case so this is how the
title
case works
you can also count the occurrences of a
particular
element in a string
suppose i have string one
that has python programming
in str2
i'll write str1 dot
and use the count function to count how
many times let's say n the letter n is
present
then i'll print
saying
occurrences
give a colon here
and then i'll pass in my variable that
is str2 so this will count the number of
times
n is present in my original string so if
you see here
in python programming we have n present
twice
similarly let's check for
g
the letter g is also present
twice
let's see for y
now y is present only once which you can
see here
okay next
let's see how the
replace function works in
python
i'm giving a comment as replace
so let's say i have a string str1
which has
hamburg
is
located in
france
so hamburg is a city which is actually
located in
germany and not in france so using the
replace method we are going to replace
france with germany
so what i'll do is i'll create another
string str2 equal to i'll write str1 dot
and then i'll
use the replace function
and i'll say replace
my string france
with
country
germany
and then we'll print str2 and see the
result
there you go
so we have changed
hamburg is located in france to hamburg
is located in germany
now coming to the final method that we
are going to explore in this
python strings demo which is
using the split function
okay
so you can split the values for each
word in a string as separate
words and store it in the form of a list
so i
write str1
i'll just copy this
i'll paste it here
and i'll change france to germany
because hamburg is actually present in
germany and not in france
and then i'll create another variable
called str2
i'll write str1 dot
and then use the
split function
now let me print both the strings first
i'll print str1
and then i'll print
str2
if i run it you see
my original string was hamburg is
located in germany and then using the
split function we have
segregated or divided
each of the words present in the
original string into separate words and
this time it is present in the form of a
list let's see what operators are in
python
now operators are generally used to
perform operations on values and
variables in python
these are standard symbols used for
logical and arithmetic operations
the value that the operator operates on
is called the operand
so here on your screens you can see the
different types of operators available
in python
first we have arithmetic operators so
arithmetic operators are used to perform
mathematical operations
it returns either true or false
according to the condition
so these are the comparison operators
you have
less than greater than less than equal
to greater than equal to we have not
equal to and we have equal to equal to
third we have
assignment operators so assignment
operators are used in python to assign
values to variables so these are the
assignment operators you have equal to
you have plus equal to
so for example you have a variable
called x
and if you say x plus equal to 7 this
means
it is x equal to x plus 7.
similarly if you say x minus equal to 7
this means x equal to x minus 7
and similarly you can
see the other assignment operators here
next up we have the
logical operators so logical operators
are used in
the expression evaluation to make a
decision if both the expressions are
true
then the condition will be true for an
and operator
for an or operator if one of the
expressions is true then the or
condition will be true
now for not
if an expression a is true then not e
will be false
we also have
bitwise operators so bitwise operators
act on operands as if they were strings
of binary digits it acts on bits and
performs bit by bit operation so hence
it is called bitwise operator
so here each value is evaluated as
zeros and ones
then we have identity operators so
identity operators are used to check if
two values are located on the same part
of the memory
two variables that are equal does not
imply that they are identical we'll
understand each of these operators in
the demo session on the jupyter notebook
and finally we have membership operators
so membership operators are used to test
whether a value or variable is in a
sequence so you have is
and is not as identity operators in
membership operators we have in and not
in now let's head over to our jupiter
notebook and we'll see
and explore all these operators one by
one
so i am on my jupiter notebook operators
in python
so let's first start with arithmetic
operators
i'll just
give a comment here saying arithmetic
operators
okay
first up we'll see the addition operator
for that let me assign
two
variables so i have assigned a variable
x to a value 10
and let's say we have the second
variable y equal to 4.
now
if i say print
x
plus
y
it will perform an arithmetic operation
that is addition
and will sum the result
of x and y and gives me 14 because 10
plus 4 is 14.
then let's say
i'll write print
x
minus y
that gives me 6 because 10 minus 4 is 6.
similarly you can have
multiplication as well so i'll write x
asterix y
that gives me
40 because 10 multiplied by 4 is 40.
similarly
let's
say x
divided by
y
it gives me 2.5 which is basically the
quotient
of these two operands
all right
now
if you were to find the
remainder you can use the modulus
operator so i'll write x modulo y it
gives me 2
so you divide
10 by 4 the remainder is 2.
now you can use the
double asterisk operator which is
basically
known as power
so the left operand is raised to the
power of right
i'll write print
x
give to asterisks and then say y
it gives me 10 000 so what basically
python does is
it will raise 10 to the power of 4 so 10
is multiplied 4 times and the result is
10 000
you can also try out another example
let's say 2 raised to the power of 4
this gives me
16.
if i say 2 raised to the power of 3
that is 2 cube and the result is 8.
you can also perform flow division
so flow division results into whole
number adjusted to the left in the
number line so if i write print
x
and flow division is
given by 2
forward slash
then i'll write y
that gives me 2 so it returns a whole
number
a generic division gives me
2.5
that has the floating point value but a
flow division will give me a whole
number
adjusted to the left on the number line
all right so these are some of the basic
arithmetic operators that are very
popular in python
next we'll move on to
assignment operators
i'll give a comment as
assignment operators
okay
let's assign a value x equal to 7
so here we are assigning the value of
7 to x
and
your equal to is an example of
assignment operator
now if i print x it will give me 7.
let's say i'll again write x equal to 7
and in the next line i'll write x plus
equal to 3
and will print x
so what python does is
it adds 3
to my original value
that x holes that is 7 so here x plus
equal to 3 means
x equal to x plus 3
so
x equal to x plus 3 can be written as x
plus equal to 3
similarly
you can also
write x
minus equal to something
say x equal to 7 and then i write x
minus equal to
3
then we'll print x
this gives me 4
because
we are subtracting the original value of
x by 3
so here x minus equal to 3 means x equal
to x minus 3
okay
similarly let's say i'll write x
asterix
equal to 3
if i run it
and print the value of x it gives me 12
because our previous x value was 4 and
now we have multiplied x by
3 so x
value now becomes 12.
let's say i'll write x
divided by
3
and i'll print x it gives me 4.0 this is
a floating point number so we are
dividing
12 by 3 and the result is 4.0
cool
if you want you can also perform
an exponent operation
or a power operation so let's say i have
x equal to 7
and then i write x
double asterisks equal to
say 2
and then we'll print x
okay there is an error here let's debug
the error
i have put a space here let's delete
that space you have to keep this in mind
now let's run it there you go so 7
raised to the power of 2 which is
basically 7 square is 49.
you can change the values and
run other examples let's say 10 raised
to the power of
3 we have 1000 as the result
okay
now moving ahead
now we'll understand about
comparison operators so i'll give a
comment
as
comparison operators
okay
let's say i have x equal to 7 and then i
have y equal to
3
if i print
x equal to equal to y
it will give me false the reason being
the value that x holds is not equal to
the value present in y these are two
different values that x and y hold so x
is not equal to y
and if we print x equal to equal to y it
will give us false
now
i'll just copy this code
i'll print it
here
and instead of equal to i'll give not
equal to
so not equal to is represented by an
exclamation mark followed by an equal to
if i write x not equal to y
this gives us true because x and y are
two different values and they are not
equal
i'll print
my code again and this time let's say
i'll write
x
greater than
y
it gives us true
because 7 is greater than 3
if i write x less than y
and hit shift enter that gives me false
because 7 is not less than 3
i'll print the code again this time
we'll see
if x is greater than equal to 3
if i run it it is true because 7 is
greater than equal to 3
and
now let's check for less than equal to
this is false because
7 is not
less than equal to 3
okay so these are some of the
basic comparison operators that are
available in python
now moving ahead we'll see
how logical operators work in python
okay
first
we look at the and operator
in python
suppose i have a value
of 7 stored in x
and then i have a value of 12 stored in
y
if i write
x greater than
2
and
y
less than 10
let's run it and see the result it gives
us false
now
and logical operators
will return true
if both the
conditions are true
and it will return false even if one of
the condition is false
so here
x is greater than 2 which means 7 is
greater than 2 is true
but
y
less than 10 which is 12 less than 10 is
false and hence our entire expression
becomes false
next let's see i have x equal to 5
and then
i'll print
x greater than 3
or x
less than
10. if i run this
it returns as true the reason being
x greater than 3 is true which means 5
is greater than 3 that is true
but 5 is
not less than 10
but
since one of the conditions is true so
the or operation in python returns us
true
now
let's see another example
i'll write x equal to 5
and
y equal to
10
i'll print
x
greater than 10
or
by
less than 20
if i run this
it returns true
so let's see our expression
x greater than 10 that is
5 greater than 10 is false but
y less than 20 so 10 is less than 20 is
true so our or operation will give us
true since one of the condition is true
now moving to the next logical operator
we have not
i'll given
comment here as r and now we'll see not
let's see i have x equal to 5 and then
i'll
x than
3
and
x less than 10
this should ideally give us true the
reason being x is greater than 3 and x
is less than 10
let's run and verify okay so this is
true now let me copy this and i'll paste
it in the next cell
now i'll replace
my above print statement with a
not operator
and we'll close our print function with
another bracket
now let's run it
so this will give us
false because
my
expression evaluates to true
but not true is false
okay
now moving ahead
let's discuss
identity operators in python
all right
so we'll start by assigning a value of
let's say
505 to x
and then in y i'll have
500 plus 5
so which is also 505
so x and y hold
the same value of 505
so i'll print
x comma y
so you can see here both the values are
same 505
for x and y
now i'll use the
logical operator that is
double equal to or equal to equal to
i'll write x equal to equal to y
this will give us true because x and y
hold the
same value of 505
but
let's check with the identity operator
so i'll write x is
y
if i run this
it gives me false
the reason being
x and y both refer to objects whose
value is
505
they are equal but they are not
referencing to the same object
now this you can verify using the id
function in python if i write id of x
this will give me the memory location
that x has you can see this is the
memory location of x
now if i write id of y
there you go so this is a separate
memory location in which
y is holding the value of 505 and hence
x is y is different
and hence it is false
suppose i write x equal to 100 and i
have y equal to 200
if i write x
is not y
this gives us true the reason being
x and y both are holding
different values so x is not y is true
let's see another example this time
we'll define
two lists
so i have a list called a that has value
let's say
5 comma
6 comma
3 comma 7
comma 1 comma let's say 9
and then
i'll have
another list
that will also have the same elements
i'll copy this and i'll paste it here
okay
if i write
c equal to a
and then we'll print
a is c
if i run this it gives us true because
we are assigning
the variable a to c and hence
the memory locations are the same for
both and hence
a c gives us true
what if i write a
is
b
now this gives us false
so here a and b are both less
they are equal but not identical it is
because the interpreter in python
allocates them separately in memory
although they are equal
okay
now let's talk about
membership operators in python i'll give
a comment as
membership operators
okay
let's see i have a list
a that has
the above values five six three seven
one and nine i'll copy this
and i'll paste it here
okay
i have
another list
b that has
different types of elements we have 4
next element is python
then we have
2
comma
7
comma let's say
simply learn
and then i have
nine
i'll run this first so i have my
two lists a and b i have printed them
let's explore how the membership
operator works so
we saw in the slides in and not in our
two membership operators
if i write 5 in a
and run it it returns me true because
you see here
5 is present in a and hence 5 in a will
return true
what if i write 55 in a
this gives us false because you see here
in the list a we don't have
an item 55 in a
so it gives us false
what if i write 4
in
b
this gives me true
you see here in b we have the element 4
so 4 and b is true
one thing i wanted to show you is
what if i write
python
in
b
you see here
it gives us false
though we have
python in our list b
but
the python i'm trying to check
is not present in b the reason being
here
python is written in lowercase
but
what i am checking
python p is
in upper case
so it is case sensitive
and hence this gives me false
let's say
i'll declare a dictionary y
equal to and within curly braces
i'll
give my key a
and i'll assign the value
of india
let's say i have another
key
b
and that has a value let's say usa
now if i check a in y
it gives me true because your key a is
present in y
now what if i check
india
in
by
now this gives me false so here
the membership operator won't work on
the values it only works on keys in a
dictionary
now let me go ahead and change the keys
to numbers i'll give one
that has india and the second key i'll
have two
now
if i change e to one
it will work fine it gives me
india
but if i write usa in y it gives me
false as i said
the membership operator won't work on
the
values it only works on the keys in a
dictionary
cool
now coming to the final section
of our demo
we'll explore about
bitwise operator
okay
so python bitwise and operator returns 1
if both the bits are 1 otherwise it will
return 0. so first let's see
7
ampersand 2.
if i run it
it gives me the value of 2.
so what python does is it will first
convert the numbers 7 and
2 to their binary equivalents that is in
the form of zeros and ones and then it
will perform the bitwise and operation
so
7 ampersand 2 the value is 2
if i write 3 ampersand
5
the value is 1 again it will first
convert 3 and 5 to binary equivalence in
the form of zeros and ones
and then it will perform the and
operation the bitwise and operation
now the python bitwise or operator
returns 1 if any of the bits is 1
if both the bits are 0 it will return 0.
so if i write
10
or
5
it gives me 15 so first it will convert
10 and 5 to binary equivalence and then
it will perform the bitwise or operation
let's see another example i'll write 4
or
i'll run it
so the
bitwise or operation gives us 12 as the
result
in programming languages conditions play
a very crucial role
they help us develop programs that can
satisfy all the business conditions and
perform well
so conditional statements are useful
when we have to decide that a certain
condition or certain part of a code
should run only if the condition is true
so the if statement is an example of
conditional statements
the program will first
evaluate the test condition
and will only execute the code block if
the test conditional expression is true
so here you can see the syntax of
if statement first we have the
if keyword and inside
parenthesis we are going to pass the
condition
and
if this condition evaluates to true then
we go inside the body of the if
statement which is this part of the
syntax
now
while developing a code for a business
problem you might have to use multiple
conditions
so the alif statement is used when we
have to check multiple conditions so
here you can see
if the first test expression evaluates
to false then you have the alif
condition
and
if the lift condition evaluates to true
then we go inside the body of the
elif statement which is this part of the
statement or the syntax that i am
highlighting
next
so sometimes you want to evaluate a
condition and take one path if it is
true
but specify an alternative path if it is
not so this is done with an
else clause
so the else code block will run if the
expression is false
so here you can see if the
condition for the if statement
returns false then we have the body of
the
else statement
and finally
after
all the if alif and else statements have
been executed we will execute if there
are any other statements which are
present outside the if condition now
moving ahead
we will use if else and lf statements to
write a program that will solve a
business problem
so based on the location and total
amount of the items we are going to find
the sipping cost
the locations are a few states in the
united states
in the if statement project we will ask
the user to enter the amount of the
package or the item
and we'll also ask the user to input the
state name
so for the different states we'll define
the conditions using the total amount of
the items and print the shipping cost
so let me take you to my jupyter
notebook where we'll
do this project
okay so i am on my jupyter notebook let
me just rename this
notebook i'll say if
statement
and
project
all right
so
let me go ahead and
give a comment i'll say
package
delivery cost
based on
the location
and
total amount
all right
first and foremost i'll go ahead and
create a variable called total
now this will be
a user input so i'm using the input
function
and here i'll pass the message as enter
the
amount
for
the item
all right
next
i'll assign
another
variable
called state this is also going to be a
user input so i'm using the input
function and i will say
enter the
state name
in
usa
so these are the two
inputs we are asking from the user that
is to pass the
amount for the item and the state in the
usa
all right
now we'll start with our first if
statement i'll write if
state
equaled equal to let's say my first
state name is texas
give a colon
make sure the syntax you are writing is
correct
now i am going to use
another if statement so this becomes a
nested if statement now
i'll write if
total which is my
item amount so i'm checking if total
amount
is
less than or equal to
150
then
i'm going to print
shipping cost
in
texas
is
let's say
30 dollars
all right
now i'll pass my next condition using
elif statement
since i am using multiple conditions so
hence
i am going to use
the alif statement this time i will
write f total
is greater than 150 and
if my total amount is
less than or equal to 250 dollars
then i'll say
print made a spelling mistake this
should be shipping
i'll say print
shipping
cost
in
taxes
is
let's say
20
so usually if your
amount of the item is high then the
sipping cost is low
so here you can see if the total amount
for the package or the item is less than
150 dollars then your shipping cost is
30
but if it is between 150 and 250 your
shipping cost is less which is 20
dollars
then i'll say else
shipping
cost
in
texas
is
five dollars
so what basically this means is
if your total is less than or equal to
150 dollars then
the shipping cost would be
30 dollars
if your total amount lies between 150 to
250 dollars your shipping cost is 20
and if the
cost of the item or the package is more
than
250 dollars
the cost is
five dollars
so this is for texas state
now moving ahead
i'll write alif
this time
we'll check the condition for state
let's say florida
i'll
use a colon here and say if
my
total is less than equal to 150 dollars
then we'll print
shipping
cost
in
florida
is
let's say 45 dollars
i'll use the ellipse statement again
i'll say lf
total
if it is
more than 150 dollars and
if it is
less than or equal to 250 dollars
i'll write
shipping
cost
in
florida
is
let's say 35
next
i'll
write my else statement i'll say
shipping
cost
in
florida
is
let's say 10 dollars
if the cost of the item is more than 250
dollars now one thing to note here is
the shipping cost is different for the
different states in the u.s
all right
now we'll move on to our
next state let me
give a space here
i'll say lf
state equal to equal to let's see we'll
take
virginia now
i'll see if total
is
less than or equal to 150
dollars
will print
shipping
cost
in
virginia
is
let's say twenty three dollars
all right
just scroll down
next i'll write my ellip
statement i'll say lf
total
is
greater than 150 dollars and
total
is
less than equal to 250 dollars
then
we'll
just copy this message
paste it here
and we'll see shipping cost in virginia
is
15
next
we'll write our
else statement else
i'll paste the message again i'll say
shipping cost in virginia is
five dollars
in case the cost for the
items is more than two hundred and fifty
dollars
now moving to our final state
i'll write another alif statement i'll
say alif state equal to
equal to let's say new jersey
if
total
is less than equal to 150 dollars
then
we'll print
just paste the message here i'll say
shipping cost in
new jersey
is
let's say 40 dollars
now i'll say lf
total
if it is greater than 150 dollars and if
total is less than equal to 250 dollars
will print
just put this within double quotes
and
i'll say shipping cost in
new jersey
is
let's say
ten dollars
i'll say else
my shipping cost
is
free
in case
the
total amount for the items is
more than 250 dollars
all right
finally
we'll have our
else statement where i'm going to print
invalid
state
name
in case the user enters any other state
apart from new jersey virginia florida
and texas
all right
so
we have our small project ready let me
just
run through it
so first we are declaring two variables
total and state and we are taking this
as user input so the user is going to
input the
amount for the item or the amount for
the package and then
the user will input the state
so we have the four states defined here
and we're checking the
shipping cost
for these four states
based on
the
amount for the items
all right
now let me go ahead and run it
so here you can see we have our first
user input enter the amount for the item
let's see
i have my amount as
125
dollars
and the next input is enter the state
name in usa i'll say
let's say florida
if i run this
it gives me the shipping cost in florida
is 45 dollars let's go to the top and
see what we have
now our total was
125 dollars which is
less than 150 and hence
it has printed shipping cost in florida
is 45 dollars
let's
run this again
this time i'll say
let's see my
item costs
255 dollars
in the state let's say new jersey
let's run it
you see here it gives us the message
shipping cost is free now the reason
being if you see
this part of the code
for state new jersey
if the
total
amount for the items is
more than 250 dollars
the shipping cost is free
now let's try for another state
this time we'll see for virginia
let's say my
amount is 190
and my state is
virginia
if i run it it gives me the shipping
cost in virginia is 15
let's check our code
so here i have entered my
item amount to be 190 dollars so it lies
between 150 and 250 dollars and hence it
has printed the message that shipping
cost in virginia is fifteen dollars
now let me enter another
state name that we have not defined
in our code let's say i have
my item amount as
290 dollars
and
the state name
i'll give us let's say colorado
if i run it it gives us the message as
invalid state which is present in the
last part of our code so
since we haven't defined any
shipping cost for colorado it has given
us the message that the state i am
trying to search for is invalid
you can check for
another state or any other country name
anything that is not
part of our
project
let's say i'll enter my amount as
hundred dollars
and this time i'll enter my state name
as
let's say ohio
and we'll run it it again gives us
invalid state
let's try out one last time i have my
package amount as 350 dollars
and let's see
my state is
alaska
again it says invalid state name because
we haven't defined
any condition for
alaska state
so this was a very simple project that
we did using
arif statement we saw how to write
nested if and we saw how to use the alif
and the
else statement
we will start by learning the basics of
loops and look at for loops in python
then we will understand about while
loops in python with its syntax and
coding examples
finally we will see how to write nested
loops in python with hands-on
demonstrations on the jupyter notebook
so let's get started
so what is a for loop in python
a for loop in python is used to iterate
over the items or elements present in a
sequence
the items present in a sequence can be
in the form of a list tuple dictionary
or even a string
a for loop in python uses the range
function to iterate over a specific
number of times
now let's have a look at the syntax of
for loop
so here on the left you can see the
syntax of the for loop so we have the
for
keyword followed by the iterator
variable then we have the in keyword
followed by the sequence it can be a
list you can use the range function it
can be a dictionary or tuple anything
and after that you have your colon
followed by
the statements that you want to execute
in the for loop
and below you have the rest of the code
and here on the right you can see
this is the
flowchart of a for loop so you have
for each item in sequence then we check
the condition if you have reached the
last item
if that is true you exit out of the loop
but if it is false you keep on
running or executing the statements that
are present inside the for loop this
will continue until and unless you have
reached the last item in your sequence
okay
now let's head over to our jupyter
notebook where we'll
see for loop in detail
and we'll explore a lot of code examples
okay so here i am on my jupiter notebook
let's start by writing a simple for loop
suppose i have a variable
say s
and it has a value which is a string
let's say simply learn
okay
now
the way to write a for loop is i'll say
for
i which is my iterator variable it can
be any valid variable name in python
in
my variable that is s
so here s becomes my sequence
i'll say print
i
so what this for loop is going to do is
it will iterate over all the characters
that are present in my string and print
them one by one
let me run it by hitting shift enter
you see here using this for loop we have
i traded over
all the letters that were present in my
string that is simply learn and we have
printed them one by one
okay
now
the print function in python provides a
parameter called end so by default
the value of the parameter is
backslash n that is the newline
character now you can end a print
statement with any character or string
using this parameter which is end
let me show you what i
meant so i'll again
have my same string simply loan
i'll say for i in
my variable
or my sequence s
i'll say print i
comma
then i'll use my end parameter equal to
and
my end parameter will have a value of
asterisk
now let me run this you can see here
this is sort of a pattern that we have
printed
so between each letter in my
string simply learn we have an asterisk
okay
moving ahead
let's see how to
use
for loop
in a list
all right
i'll declare a list called
programming
and this list will contain
a few programming languages let's say we
have java and then
the next item we have in the list is
python
next we have ruby and then
we'll have html
okay
so
i'm going to print
all the
individual items that are present in my
list using the for loop
so i'll use the same syntax i'll write
for
this time i'll use my iterator variable
name as iter which means iterator
for iterator or iter in
my sequence which is programming
i'll say print
iter
let's run it you see here we have
printed all the items in my list one by
one
java python ruby and html
all right
now let's see
an example how you can find the average
of a list of numbers using for loop so
i'll give a
comment saying find the
average of a
list of numbers
okay
so here
first of all we'll declare a
list of numbers with variable list
underscore num equal to
it will have a few numbers let's say 20
25 10 50 and
40.
let's make it 45
now to find the average of a list of
numbers
first i'll declare a
variable called sum that will have
a value of zero so we have initialized
the sum variable to zero
then i'll start my for loop for i
in
my sequence that is list underscore num
which is
this variable
give a colon i'll write sum
equal to
sum plus i
so here
just give a space to make it more
readable
so i'm adding
all the numbers in my list and we are
storing the result in the variable sum
then we'll say
sum
equal to
i'll pass in my variable that is sum
then i'll say print
average
equal to
now our average will be
my variable sum divided by
the length
of my
list that has all the numbers
let's run this you see here
so a total sum of all the numbers
present inside the list is 150 and the
average of
all these numbers is 30 so 150 divided
by 5 is 30
all right
let's see how you can use a for loop
using a tuple
so let's declare a variable called num
is going to a tuple of numbers
and we have 30 45 60 50 and let's say 70
as the numbers inside the tuple
i'll say sum equal to zero
then we'll have our for loop for i in
my sequence that is num
i'll say
sum equal to
sum plus i
so here we are just adding the values
that are present inside the tuple
i'll say print sum
so here you can see we have
printed
all the values present inside the tuple
one below the other now if i shift my
print statement to here
you can see here this is my
sum of all the numbers that are present
inside the tuple
so make sure you have
the current
indentation
now let's see how you can use the range
function in python
okay
so you can use the range function to
iterate over a range of values
or numbers
using a for loop
the way to do is i'll say for i in
my function range
i'll give my first index at 1 and my
second index at
or my end index at 10
so this will go from 1 till
9 and exclude the 10th index
i'll say print i
you see here
for i equal to range 1 to 10 we have
printed all the numbers starting from 1
till 9. so
the last index that is 10 is
exclusive in the range function
now in the range function you can also
give a third parameter that stands for
step
so that you can skip a few steps and
print the next value let me show you
what i mean
say i write for i in
range
0 which is my starting index
10 which is my end index
and i'll have a step size of 2
give a colon
i'll say
display
values
with
a
step
size of
2.
give a comma here and my variable that
is i let's print it
there you go
so we have printed
the values with a
gap of two so it starts from zero then
we are jumping two steps and then we are
printing two then again two steps we
have four six and eight so we are
skipping
one value
and printing the next value
in my sequence
ranging from zero to ten
all right
now
let's write a program to print
a table of a given number
so i'll give a comment as
program
to
table of a
given
number
all right
so i'll pass my
variable n
which is going to be a user input so i'm
using the in function and inside the in
function i'll use the input function to
take the user input
i'll give my message as enter the
number
i'll say for
i in
range
from 1 to
11
i'll say
multiply which is mul here
and
asterisk i
so basically what i'm doing here is
i'll take a user input of the number
let's say we want to print the table of
5
so from
1
till 10 will have the product of the
numbers
let me print it
i'll say print
n
comma
within double quotes i'll give my
asterisks
comma
i
comma
within double quotes i'll say equal to
and then we'll have our
variable mul
let's run this
enter the number i'll give 5 and hit
enter
there you go
so here we have the multiplication table
of
my number 5 so you see
5 into 1 which is 5 5 into 2 is 10
then we have 5 into 7 35 5 into 9 is 45
then
our last index which ends at 10 so we
have 5 into
10 that is 50
all right
this is how you can create a simple
multiplication table using for loop in
python
now we can also use the range function
with a sequence of items
the len function can be combined with
the range function to iterate through a
sequence using indexing
i'll show you
an example here let's say we have a list
called list 2
and here we have
a list of programming languages let's
say
c plus you can either use a single quote
or a double quote to represent the
text
values in a list
the next programming language i have is
java
then let's say i have python and we have
r
okay
so i can write for i in
range
here i can use the length function
and i'll say
list
2
give a colon
then we'll
print hello
and i'll say
list 2 of i
so what it does is
my iterator will iterate over
the list of programming languages i have
here
and it will keep on iterating
till
the length of the list
and then i am printing my message as
hello
and it will take each item
from the list using the index number
if i run it you can see here it says
hello c plus plus hello java hello
python and hello r
cool
now let's see how you can use
nested for loops in python
i'll say nested for loop
as my comment
let's see i have a
list
of company names
my first company i have in my list is
let's say apple
pwc
and then we have
uber
so here i'll write for i in
companies
i'll say print
we
will
display
each
letter
of
i'll say plus i
now i'll use my second for loop sync for
letter in i
will print the letter
let's run it and see our result
there you go
so here we have used
two for loops so that becomes a nested
for loop we have my outer for loop and
then
we have our
inner for loop so in the outer for loop
we are just printing
the
name of the company so here we see we
will display each letter of
plus i which stands for
my company name google so you can see
below we have
displayed each letter of google using
the
inner for loop similarly we have
for apple you can see a p p l e we have
pwc and then we have uber
so this is how you can use
multiple for loops
in python
now let's see how you can use a for loop
with else clause
so i'll give a comment for loop with
else clause
so i'll write for i in
range
0 comma 10 comma i'll give a step size
of 3.
i'll say print
i
and after this
python gives you the flexibility to use
an else clause
after the for loop so i'll write
else print
the
loop has
completed
execution
so this is my message
that we are going to print after we have
printed all the
elements
that are present inside this range
function
let's run it you can see here we have
printed
the value starting from 0 with a step
size of 3 so we have 0 3 6 until 9
and then
after that we have our else block
printed
which has the message the loop has
completed execution
cool now let me show you
two more
important feature that you can use while
writing a for loop one is called the
break statement the other one is called
the continue statement
so in python you can break the for loop
and end it before it has actually run
all the elements in the i table using
the break statement
so let me show you a simple example if i
write for
just give a space here
i in
range
let's say from 1 to 10
i'll use an if condition
saying if i equal to equal to 6
then
break and come out of the loop
next we'll print i
so here what we are doing essentially is
we are iterating over
all the values from 1 to 10 and whenever
the i value becomes 6 we come out of the
loop and print
all the values we have iterated so far
let me run it and we'll see the result
the yuko so here our i value started
from 1
we printed 1 2 3 4 5
and then
our i value reached 6 then we use the
break statement to come out of the loop
all right
now
you can also skip the execution of
further statements in the for loop
during the titration using the continue
statement in python
so when a continue statement is executed
the for loop continues with the
execution of the next element in the i
table
it does not complete all the statements
in the for loop body
so again we'll
give a comment
say continue
okay
so i'll write for i in
range
again from 1 to 10
give a colon i'll say if
my i value
is equal to equal to 6
then i'll say continue
then we'll print
i
let me run it and we'll see the result
okay so if you notice this
output so we have printed values from 1
to 5
and when my i value became 6
we skipped printing 6 and we
moved on to the next element in the
iterable which was 7 then we printed 8
and 9.
so this is how you can use the break and
continue statements in python
all right
now we'll see a program to display the
total goals a player has scored
so here we are going to iterate over a
dictionary
so i'll give a comment program to
display
the
total goals
clear has code
all right
first of all
i'll declare a variable saying clear
name
and let's say we have the player name as
carmelo
all right
i'll declare a
dictionary called ghouls
and within
curly braces i'll have
my first
clear name addition
let's see edition has scored
14 goals then we have let's say
burnett so burnett is my key here and
then we'll have
value in terms of goals let's say three
and then we have our third player let's
say carmelo
and carmelo has scored let's say seven
goals
now i'm going to write my for loop so
i'll write for
my i table name here is player
in
my sequence name is goals so i'll say
goals
i'm going to check if
my
player
is
equal to equal to
player name
i'll say print
the goals scored by the player
so i'll
pass my dictionary name and within
square brackets
i'll say
clear
let's
use the break statement
and then
i'll say
else
will print
my message would be
no player with
that name
found
let's run and see the result
all right so here
what we did was initially i declared a
variable called player name that had the
value carmelo
and since carmelo was present inside my
dictionary
named goals you can see here we have
carmelo who had scored seven goals
so i i traded over
my sequence goals and i checked if my
that is player is equal to equal to the
player name which is carmelo since this
carmelo is present inside my dictionary
name so we printed the goals that were
scored by carmelo that is 7.
now let's say i change this player name
to
we have let's say messi
now since messi is not present inside my
dictionary goals if i run this
it will print no player with that name
found the reason being message is not
present inside
my dictionary called goals
cool
now
we'll see two more
examples
this time
we are going to
print the cube of
numbers using for loop
all right
so first of all i'll declare a list
which will have a list of numbers let's
say 2 5
7 4 8 and let's say 6.
then
i'll pass in a
empty list so i'll declare within
empty square brackets
i'll say for i in
my sequence name that is num
i'm going to use my empty list cube and
then followed by the append function
and inside the append function we'll
have our
cubes of the number so i'll write i
i'll use the double asterisk operator
and then i'll say three
after that we are going to print
my
list name that is cube
let's run it
there you go
so you can see here
first we have
the list of the numbers here
and then
we have printed the
cubes of these numbers in a pattern
let's say
bring this print statement here and i'll
run it again
now this is much more readable you have
2 cube is 8 5 cube is 125 7 cube is
3
43 then 4 cube is 64 8 cube is 512 6
cube is 216
all right
now coming to
the last example in our demo section of
this
for loops in python video
will
write
a program to print a pattern
i'll say pattern printing
all right
so we are going to print
a right angle triangle
for that i am going to take
my first variable called n which is
going to be
a user input to enter the number of rows
so using the input function
i am passing the message
enter the
number of
rows
i'll say for i in
range
0 till my user input n
[Music]
give a colon
i'll use my
inner for loop
this is
going to be the number of columns so
i'll say for j in
range
0
comma i plus 1
give a colon
and
i'll print
my star pattern so i'm using asterix
and i'll use my end parameter
i'll have my double quotations
and then
we'll say
the pattern
so here what i am doing is i am taking
the number of rows from the user
and i'm iterating
from 0 till n which is my user input and
then
we are
assigning another for loop for the
number of rows so that ranges from 0
till i plus 1
then i'm printing my star
let's run it and see the output
let's say i'll enter the number of rows
as 6.
if i hit enter you can see here we have
our right angle triangle printed here
so initially
my
i value is
0
so here
my j value becomes from 0 till 1 so we
have just 1 star printed
in the next iteration my i value becomes
1
so from
0 to 1 plus 1 that is 2 we have 2 stars
printed the next iteration my i value
becomes two so two plus one is three
again so we have three columns here so
three stars printed so on and so forth
all right if getting your learning
started is half the battle what if you
could do that for free visit scale up by
simply learn click on the link in the
description to know more
so what is a while loop in python
a while loop specifies a condition or a
block of code that is to be executed
until the condition evaluates to false
or the loop is explicitly ended with a
break statement
moving on to the next slide
so here you can see the syntax of a
while loop
so a while loop is defined using the
while keyword and then you have the
expression followed by a colon
after that you have the statements
inside the block
the statements are executed until the
condition evaluates to false
now on the right side you can see the
flowchart to show
all the steps
to execute a while loop so you can see
here we have the test expression if the
test expression evaluates to true then
we execute the statements that are
present inside the while block
but if the condition is false we will
exit out of the while loop
now before i move on
i have a question for you
so here is a python quiz question
i want you to tell me the output of the
below code so this is regarding a list
i have declared a list called alpha that
has d
f and c as its elements then i am saying
alpha plus equal to ka which is again a
string since it is within the single
quotes then i am printing the list
now you need to tell me what is the
right answer you have four options here
a b c and d the first option is d comma
f comma c comma k a combined
then we have k a in the beginning of the
list
followed by dfc
the third option or the c option is d f
c k a k being
individual elements
and the last option the d option is k a
d f c
please go ahead and solve this question
and put your answers in the comment
section of the video
we'll be more than happy to know from
you
all right
now let's
go ahead and start with our demo
so here i am on my jupyter notebook let
me
rename my file i'll say
while looping python
demo
okay
so
let me start by writing a simple while
loop i'll declare a variable called i
equal to 0
then i'll start with my
while loop
i'll write my while keyword
and this will run till my i is less than
10 let's say
i'll give a colon
and if i hit enter it will come to the
next line you can see the indentation
here which is being maintained i'll say
i equal to
i plus 1 so i am incrementing my i value
then i'll say print
i
and i'll use my end parameter
and i'll say end
within
single quotes i'll say hash and give a
space
then let me say print again
so here my while loop will run until my
i value is less than 10
so we are continuously incrementing the
i value and printing the i value
let me run it there you go you can see
the result here
we have printed the i values starting
from
1 till 10
and after that
we have come out of the loop
and you can see the
hash symbol being used here because we
used our end parameter as has
so by default it is a new line character
but we have explicitly defined our
end parameter as has followed by a space
cool
now let's move on to our next example in
this video on while loop
i'll define a variable called count
and i'll assign a value 0
i'll say while
my count is
less than equal to 5 i'll give a colon
come to the next line and i'll print
the
condition
is
true
and then i'll say
count
equal to
count
plus 1
and then i'll say
end of loop
let's run and see our result
you can see here we have printed our
message the condition is true five times
because
our expression is being evaluated five
times here
in the sixth time our count is no more
less than equal to 5 so we
end the loop and here you can see the
message end of loop
cool
now moving ahead
you can also use
the break statement
in a while loop let me show you how to
do it
i'll say while true
so i am
declaring my
while loop to be true
and i'll say
please
type
your
name
and i'm going to
take my
name as input from the user so i am
specifying the
input
function
i am going to check if my name is equal
to equal to let's say
gilly
then i should give a colon here
i'll break out of the loop
and then we'll
thank you
you
typed
the
correct name
all right
so what i'm doing here is
i'm going to run this loop till the user
enters the correct name so i have
declared my name as gilly if you enter
any other name apart from gili
this while loop will
continue to run and execute
run it okay
so here it says please enter your name
i'll let's say say john
if i run it
it is again asking me please enter your
name let's say this time i'll say ami
you can see here it is again asking for
the
name so i'll enter my name let's say
hopkins
again
our entered
user name doesn't match
the name that we have provided in the
code let's say this time i'll say gilly
if i hit enter you can see we have our
message thank you you typed the correct
name
okay
now moving on to the next example we
will see how to find the least common
multiple of 4 and seven
so i'll give a comment as
lcm of
four and seven
now you would know
it is 28 but we are going to find out
with the help of
a python while loop so first i'll
declare a variable x equal to 0
i'll say while
my expression is true
i'm going to increment my x value to 1
i'll say x
plus equal to 1
this means x equal to x plus 1
i'm going to use
an if statement and say if not
and here we'll pass the condition
x
percentage 4 or modulo 4
or
x
percentage 7
then i'll say break
finally we'll
print our message saying x
comma
and i'll say is
divisible
by
four and
seven
say both four and seven
okay
so what i am doing here is
i am taking my expression while true
i'm incrementing the value of x
each time and checking if
this is true or not
now at the first instance when my number
x is divisible by both 4 and 7 i'm
coming out of the loop and we are going
to print this now let's see
what's the answer there you go you can
see here 28 is divisible by both
4 and 7 and hence the lcm of 4 and 7 is
28.
so this is the least
number which is divisible by 4 and 7.
all right
now you can also use the continue
statement
how you use the break statement to
come out of the loop you can also use
the continue statement to continue
running the loop
so i'll say
i equal to 0 while i is less than 10
so this is my expression my loop is
going to run until i is less than 10 i
am going to increment the value of i
i'll say i plus equal to 1
if
let's say i set my condition if i equal
to equal to let's say 6
then i'll say
continue my execution and skip the
current step where
i value becomes six
then i'll say print i
let's run it and see the result
okay you can see here we have printed
one two three four five and here you can
see we have skipped the execution where
i value became 6 and continued with the
next iteration 7 8 9 and 10.
so this is how you can use the continue
statement and the break statement in a
while loop
all right
now moving ahead you can also use the
else statement in a while loop now let
me show you how to do it
i'll say i equal to
1 then i'll write while i is less than
let's say 5
i'll say print i
then i am going to increment the value
to
i plus equal to 1.
now here you can use the
else statement and say print
i
is
not
less than
5
let's run it you can see here
we
ran our loop until i value was less than
5 so we printed 1 2 3 and 4
when i value became 5
we printed
i value is not less than 5.
cool
now moving ahead
so you can
use inbuilt functions inside a while
loop let me show you
how to use the
pop function and remove the elements in
a list using a while loop
so i'll declare a list
of numbers let's say 1 comma 2 comma 3 4
and we have 5 so these are the 5
elements that are present inside list a
i'll say while a
so i'm iterating over all the elements
in my list
i'm going to say print a dot i'll use
the pop function
so
what pop does is it is going to remove
the elements
from the end of a list
then i'll say else
there
are
no elements
left
in the list
all right
let's run it and see the result you can
see here we are removing
the elements one by one from the end of
the list so first we popped out five
then four three two and one and after
that we had no more elements left in the
list so we printed there are no elements
left in the list
okay
now the next program we will take
numbers as input from the user and
calculate the average
as long as the user enters a positive
number
so i'll give a comment
average of
positive numbers
cool
okay
so i'll start my program i'll declare a
variable called num
which has a value 0
i'll declare a variable called count
which also has a value 0
then i have sum
which has a value of 0
i'll write while
my
number is greater than equal to 0 so
this condition
is for accepting only positive numbers
i'll say num equal to
i'm going to take the positive numbers
from the user
so i'll
pass an input function i'll say enter
any
positive
number
then i'm going to say if
my number is greater than 0
i'll say
count equal to
count plus 1
let's make this
greater than equal to 0
then i'll say sum
equal to
sum plus
my number
so here i am keeping track of the
numbers that we have
entered and here we are calculating this
sum that is the cumulative sum
then i'll say
avg
which is to find the average
i'll say sum divided by my variable that
is count
then
i'm going to print
total
i'll say total
sum of
numbers
give a colon
followed by a space
give a comma i'll say sum
then
i'll
say
average
give a colon
followed by a space
and i'll pass in the variable avg
alright
so here i have my
program ready where we are using a while
loop and
an if statement
to
take numbers as input from the user and
calculate the average as long as the
user enters a positive number
so let me run it
okay it says enter a positive number
i'll say let's say five
again it's asking for a positive number
i'll say
seven
let's say 10
and this time i'm going to enter a
negative number so i'll say minus
6.
if i run it you can see here
the total sum of numbers
5 plus 7 plus 10 is 22
and the average is 22 divided by 3 which
is 7.33
all right
let me give a space here for more
readability
we are going to try it again
i'll say 40
50
30
and
let's say 100
this time i'll enter a negative number
let's say minus 90.
okay so you can see here
i have entered four positive numbers 40
50 30 and 100
so the sum of numbers is 220
and the average is 40 plus 50 plus 30
plus 100 which is 220 divided by 4 which
is 55
cool
now moving on to the last
demo in this while loop with python
tutorial
so here we are going to
guess a number so the user is going to
give a number between a certain range
and based on a random input generated
from the program
we are going to guess
the random number
all right
so for that
i am going to start by importing my
library called
random i am going to
say n
equal to
random
dot
rand int which is a function to generate
random integers i want to generate
between 1
and 100
let's go ahead and print that number n
then
i'll use a variable called guess
which is going to be
a user input
so i'll say input which is my function
and i'll give the message enter an
integer
between
1 to let's say 100
okay
then i'll start my while loop saying
while
n
not equal to
my
variable that is
guess
i'll say if
my
guest number is less than n
i'll print the
message as
your
guess
is let's say low
then again i'll say guess equal to
i'll take the
user input
just copy this message
and we'll print it here
okay
now
i'll say
alif
if my
guess is
more than my random integer
will print i'll just copy
this we are going to print
your guesses
let's say hi
then we are again going to
ask the
user
to
guess a number between
1 to 100
and after that i'll say
else
will print
you
guessed it correctly
then we'll
break out of the loop
and finally i'll just
print it
okay
so what we are doing in this game is
before that let me just give a
comment as guessing game in python
so first of all we are generating a
random integer using the library called
random so the integer
will lie between one and hundred
i am going to print that integer
after that i am taking a user input
so i am asking the user to enter an
integer between 1 to 100 and i am
checking if my
random integer
is not equal to my
user input that is guess
and if that guess
is less than my random integer i am
going to print your guess is low
then i am again asking the user to input
an integer between 100
then i'm saying if the
guest
value is more than the generated random
integer
will print your guesses high
then after that i'm again asking the
user to input an integer
and in case
the random integer
matches with the
guest number will print you guessed it
correctly
all right let's try this out
okay so here you can see
so my program generated a random integer
48 that lies between 100
so
our loop will only stop executing when
we
enter our
number as 48
otherwise it will keep on running and
asking you
to enter an integer
let's say i enter
50.
you see here
your guest value that is 50 is
more than
the random integer 48 so we have the
message
your guess is high
let's say i'll say 30.
this time my guess is low you can see it
here
let's see i'll
take my
number as
300. you see here
this time my guess is high which is more
than 48
but if i say
my user input to be 48 and if i
hit
enter there you go we have our message
printed you guessed it correctly
all right
choose from over 300 in-demand skills
and get access to 1000 plus hours of
video content for free visit skill up by
simply learn click on the link in the
description to know more
what is a nested loop
python programming language allows you
to use one loop inside another loop
this is known as a nested loop it is
present inside the body of the outer
loop
the inner or outer loop can be a for
loop or a while loop
the outer for loop can contain a while
loop or an outer while loop can contain
a for loop inside it in python nested
loops the outer loop can have more than
one inner loop there is no limitation on
the chaining of loops
now you can see on your screens the
basic syntax of writing a nested loop in
python
you have the outer loop followed by the
inner loop and the statements inside the
inner loop and finally you have the
statements of the outer loop the last
three lines consist of the body of the
outer loop
now talking about the various ways of
writing
nested loops in python
so with python you can write a for loop
inside
another for loop or
you can have a while loop declared
inside another while loop you can see it
here
so using python you can use both for
loops and while loops together
the outer loop can be a for loop and the
inner loop can be a while loop you can
also write nested loops having a while
loop outside and for loop inside so now
that you have learnt about the basics of
nested loops let's look at an example of
printing patterns
so in the code here
we have used
two for loops to get our
right angle triangle containing
asterisks or stars
so
we have declared rho equal to 7 which
means we need seven rows to be printed
you can count it here these are seven
rows
hence we have defined it as
rho equal to seven
now the outer for loop ensures we have a
total of seven rows
so we have defined a range
from
1 to row plus 1 that is 8. now the inner
loop is the total number of columns in
each row
so for each iteration of the outer loop
the
columns count gets incremented by 1.
so for the first titration of the outer
loop the column count is 1 in the next
iteration it is 2 and so on
the inner loop iteration is equal to the
count of the columns and for each
iteration
in an inner loop we print a star
so for the first iteration when i value
is 0 it will first print a blank
when i value becomes 1 then your j range
becomes 1 comma 1 plus 1 which is 2 so
it will print
1 star here followed by a space
when i value becomes 2 your j range
becomes 1 comma 3 so it will print
2 stars
then again when i value becomes 3 your
range becomes one comma four so it will
print three stars so so on and so forth
now let's see
when you should use a nested loop in
python so nested loops are mostly used
to work with multi-dimensional data
structures such as printing
two-dimensional arrays
i treating a list that contains a nested
list etc
you can use python nested loops to print
different star or number patterns as
well now let's
head to our jupyter notebook to do some
practical hands-on demonstrations to
understand nested loops in python better
okay you can see here i am on my jupyter
notebook first of all i'll
rename my
notebook as nested loops
in
python demo
click on rename
all right
now let's see our first example
so here
we are going to print the items in a
list one by one but each letter in an
item should be separated by the at sign
which is basically the add the rate
symbol that you use in your email ids
all right
and for
the first demo we'll be using nested for
loop
so let's start
i'll create a list
which will
have the names of the
fruits
let's say we have
mango
we'll give a comma
let's say i have apple
grapes
and let's say we have banana
all right
now i'll
create my outer loop so i'll say
for
fruit
now this variable can be any valid
python variable this is basically known
as an iterator on an iterator variable
so i'll say for fruit
in
my list which is list underscore fruits
that i have declared in my
first line
i'll give a
colon
and then
declare my inner loop i'll say for i in
my variable or the iterator that i had
declared in the previous line which is
fruit
i'll say
i
and then
i'll use
the end parameter that will have
the add sign
and then
i'll print
a blank
so this is my first
nested loop that i have created so i
want to i trade through all the items
present in my list underscore
fruits
variable
and for each item
in the list i want to make sure
that each letter in an item should be
separated with the add sign
so let me go ahead and print it so that
you can see the result the hugo
so here you can see we have printed the
different items that were present in my
list which was list underscore fruits
and
for each item
the letters
in the item have been separated by the
add sign you can see here
all right
if you want you can change this symbol
to let's say
star
if i print it
you can see the difference in the result
now we'll see our second example where
we are going to print the values of
items
in two lists together
so let me create a
list called
color that will
have the different colors such as red
we have green
and let's say blue
and the next list i'm going to create
will have three items
the first item is
apple
then we have
veggies
and then we have
shirt
now
now to print the values of the items in
these two lists together i'm going to
use two for loops again
so i'll say for
my iterator variable let's say x in
my
first list which is color
so i've declared my outer loop and now
i'll say for
another iterator variable let's say y in
my second list items
i'm going to print
x
comma y
and after that
will
print a space
so first of all
my outer for loop will
iterate through the items
that are present inside
color list
and for each color we are going to
iterate through
the values that are present inside
items list
now let me go ahead and print it
you can see it here
first we are printing red apple red
veggies and red shirt then we have green
apple green veggies and green shirt
for scroll down you can see blue apple
blue veggies and blue shirt
okay
now coming to our third example
here we are going to print a right angle
triangle with
10 rows we have seen a similar example
in the slice where there were seven rows
now we are going to print a right angle
triangle with 10 rows
i'll give a comment
let's say
right triangle
okay
so i'll start my
for loop i'll say for
any
iterator variable let's say i in
range
i'll pass my range as 11 so it will
go from
0 to
10
then i'll say for
j
in
range i
so this will
take the number of columns
i'll say print
within double quotes i'll give my star
because i want to print a star pattern
for the triangle
and i'll end with a
space
then i'll say
blank
so there won't be any space between
the different rows
now let's print the result there you go
so here you can see we have a right
angle triangle of 10 rows you can count
the
number of rows and also we have the
number of columns as 10.
so when i value is
one your g range also becomes one so we
print one star then when i value is two
we are going to print two stars when i
value is three we are going to print 3
stars
and
we are using the end parameter as a
space
ok
now let's go ahead and
print a right angle triangle using a
nested while loop so unlike the for loop
the while loop
doesn't have a pre-compiled iterable
sequence
the while loop keeps executing the code
until the expression evaluates to true
so
i'll
start with the
variable i equal to 11 because i want to
10 rows
that will contain
my star pattern
now i'll declare my first while loop
i'll say while i is
greater than 0
so my loop will continue
until i is greater than 0
i'll see z equal to 11
then i'll use my inner
while loop i'll say while
j is greater than
i
will
star
and i'll use my
end parameter as space again
then we are going to decrement
j by
1
i'll come out of the inner while loop
and i'll say i equal to i minus 1 so we
are also decrementing
the first
variable i by one and now i'll say print
okay
so let me run this
you can see it here we have the same
pattern printed
earlier we saw this using
two for loops and now we have created
the same pattern using
two while loops
all right
now
moving to our
next example where we'll see how to
append
tool list so first of all i am going to
declare
list 1 and list 2
and we are going to append the elements
of both the list into an
empty list called result
so i'll give a comment
append
two
lists
okay
so first i'll declare my
list one
now these are
list of numbers let's say i have
10 25 and 30 as my
elements in the first list
and then i'll declare my second list
which will have let's say 60
15 and 50.
okay
now i'll declare
an empty list called result
and after that i'm going to start my
outer for loop i'll say for i in
my list 1
then i'll say for
j
in
list
2
i'll say result which is my
empty list that i have declared
then i'm going to use the append
function that is
inbuilt in python
i'll say i plus
j
so this will make sure will append
the values from both the list into
my
empty list which is result
then i'll say
result
okay let's run it there you go
so what we are doing here is i am adding
each element in list 1 with all the
elements in list 2. if you see here 10
plus 60 is 70 then we have 10 plus 15
which is 25 10 plus 50 is 60. similarly
25 plus 60 is 85
25 plus 15 is 40 then
25 plus
50 is 75 and similarly for 30 plus 60 30
plus 15 and 30 plus 50
great
now
moving to our next example
we are going to see how you can multiply
the values in
two lists
so i'll give a comment
saying multiplying
two lists
i'll declare my first list which is list
one
with 2 comma 4 and let's say 6
then i'll have my list 2
with the
same elements 2 4 and 6.
start my outer for loop for i in list 1
then i'll say
for
j
in
list
2
i'm going to
show you another feature that you can
use while implementing
nested lists
that is to use
continue or break
so i'll say if i equal equal to z then
i'll continue
after that we are going to print
the value of
i
followed by
the
asterisk
then
the value of g
will give a comma
then within
single quotes i'll say equal to
then i'll give the operation i
multiplied by
j
so this is how you can multiply
the elements in two lists
so i've declared my list one my list two
then i'm using two for loops and
whenever my i value is equal to equal to
j will skip that step and move on to the
next iteration
let me run it and show you the result
so if you notice here
i haven't
multiplied
2
and 2
the reason being i have used this
if condition
whenever i was equal to j we continued
with the next iteration similarly there
is no
output for
4 multiplied by 4 or 6 multiplied by 6
but for the remaining we have our result
2 multiplied by 4 is 8 2 multiplied by 6
is 12 similarly
4 multiplied by 2 is 8 4 multiplied by 6
is 24
6 multiplied by 2 is 12 and 6 multiplied
by 4 is
24.
so
continue and break our two statements
that you can use inside nested loops in
python
okay
now
we are going to
write another nested loop using a while
loop and a for loop to check whether a
number is a perfect number or not
so basically in this program we are
going to print the perfect numbers
between 100
now a perfect number is a positive
integer that is equal to the
sum of its proper divisors
so the smallest perfect number is 6
which is the sum of 1 2 and 3 so these
are the
perfect divisors of or proper divisions
of 6 1 2 and 3. if you add them the
value is 6 another example is 28
the proper divisors of 28 are 1
then you have 2
4
7 and 14 if you add them the value is
28.
so here we will iterate the first 100
numbers using a while loop so for each
iteration of the outer while loop the
inner for loop executes from 1 up to the
current outer number to check if the
current number is a perfect number or
not
okay
so i'll give a comment
saying
perfect number
cool
so i'll first declare a variable called
a which will have a value of one then
i'll say
while
my a is
less than equal to
100
then i'll declare another variable
called y underscore sum which will
have the value of 0
after that i'll pass in my
inner loop which is the
for loop i'll say for
i in
range 1 comma a
i'll say if
a
mod
i is equal to equal to 0
then we'll say y underscore
sum
equal to
y underscore sum
plus i
then i'm going to say if
my
y underscore sum value is equal to equal
to
my e value then it's a perfect number
so i'm going to use a print statement
saying print
perfect
number
give a colon
then i'll give a comma and
print my variable e
and finally we are going to increment
the value of e to 1.
now let's run it
you can see it here
between 100 we have two perfect numbers
as i mentioned earlier 6 and 28
okay
now coming to the
final example in our demo on nested
loops in python
here we are going to print each element
in the list five times
so
i'll first declare my list let's say
fruits
which has
apple then we have
orange
and let's see we have kiwi
so i'll say for
a nitrater
fruit in
fruits
i'll declare a variable called count and
initialize it to 0
then i'm going to use a while loop
saying while count is
less than 6 since i want to print the
items in the list 5 times
then i'll say
fruit
and i'll use my end parameter as a space
then we are going to increment count by
1
and finally i'll print it
let's run it you can see it here i
printed each element in my list fruits
five times you can see it here okay so
i'm on my jupyter notebook first of all
let's rename our notebook to
looping techniques
okay
i'll just increase the
size
all right
okay
so let's see how you can arrange the
values in a list using for loops with
python sorted function
so i'll create a variable called num
and
i'll assign a list let's say it has
values 2 5
10
4
i'm taking just random values
let's say 36
50
and 49
so this is my list now i want to arrange
the
items in this list
in either ascending or descending order
so for that i can use a for loop i'll
say for i which is my iterator variable
in
and after this i'm going to use the
python sorted function
and inside the function i will pass in
my variable which is num
then i'll give a colon and say print i
so let's
hit shift enter to
run it
okay
you can see here
so python by default
has sorted the elements in the list in
ascending order so we have 2 4 5 10 10
36 49 50 and
50.
now let's learn how you can sort the
values in a list using a for loop in
descending order
so
i'll just
copy my above cell of code
we'll paste it here it will help
save us some time
so i'll say for i
in sorted
i've given my variable num
after this
i am going to pass in another parameter
called reverse
equal to
i'll say true
now reverse equal to true will make sure
python will sort the list in descending
order
if i run it
you can see the difference we have
sorted the elements in the list num in
descending order now so we have 50 50 49
36 10 5 4 and 2.
okay so this is one of the
techniques that you can use
to sort the elements in a list using a
for loop
now similarly you can also sort string
elements alphabetically in a list and
ascending or descending order
so for that i'll create a variable
called players let me just scroll down
then i'll create a list
which will have the
names of football players let's say we
have messi
then
let's say we have
ronaldo
then we have
salah
and then we have let's say harry
okay
i'm going to say for i
in
my function sorted
i'll say
i'll give a comma
and again use reverse equal to true
so
this is going to sort
the
items in my list players in descending
order of
the alphabets
then i will give a colon and say
print i
let me run it you can see here
the names of the different football
players have been sorted in descending
order of
alphabet so we have s appearing first
then r m and h so salah ronaldo messi
and harry
all right now let's move ahead
now we are going to create a dictionary
of
key value pairs and sort it
so i'll create a dictionary called d
which will have
a few key value pairs so my first key is
f and the value is let's say 1
then my second key let's say is b
and the value is 4
i'll give a comma
my next key is a and the value is let's
say 3
after that my next key is e
and the value is let's say 9
and finally we have our last key which
is c and the value is 2.
now to sort this dictionary i'll say for
i
in
sorted
i'm going to use the
items method i'll say sorted d dot items
and then we'll print i
let me run it and show you the result
you can see it here
our dictionary has been sorted in
ascending order of the dictionary keys
so we have a b
then c there is no d here
after that we have e and then f
cool
now you can also sort the
keys and values separately let me just
copy this and i'll show you
i'll paste it here
and instead of d dot items i'll just say
d dot keys
if i run it
you can see here we have
sorted only the
keys in my dictionary
now to sort the values instead of items
you can just write values
and here you can see we have
sorted the values in the dictionary d in
ascending order again so we have 1 2 3 4
and 9.
all right
now
we will understand how to use the
reverse function in loops to reverse the
items in a list
so i'll again
create my
list called players which will have
messy
let's say again the next player is
ronaldo
and then we have
salah and then we have harry
okay
now to
reverse the elements in this list called
players i'll say for
i in
then i'll use the reversed function and
pass in my list called players
give a colon and then say print i
let's run it
here you can see
we have reversed the
elements in my list called players so we
have harry first then salah ronaldo and
messi in the end
cool
now moving ahead
we'll see how to use the filter function
in loop and filter specific elements in
a list based on some conditions now to
give the condition we'll be using an
anonymous function in python that is
often called as the lambda function
to do this
i am going to create a list
called animals
i'll give my square brackets
and inside these square brackets
i'm going to
pass in the elements in the form of a
dictionary
so to pass in a dictionary we need to
have key value peers
so my first key is name
let's see
my animal is
dogs
i'll give a comma
then my next key is the age let's say
dog's age is 11
so this is my first
list element which has been passed in
the form of a dictionary
i'll create another curly bracket and
we'll have the same keys
this time let's say
my animal is lion
let's make it dog instead of dogs
okay
give a comma and then say
age
let's say the age of the line is 30
i'll give a comma
we'll go to the next line
and this time
we are going to have another animal
i'll say
elephant
give a comma
let's see the age is
63
i'll give a comma
and then we'll have our final
element in the list
let's say the name of the
animal is leopard
give a comma
then we'll have the age of the leopard
let's say
the age is 18
so we have our list ready
now
using a for loop
will filter
the elements in the list giving a
specific condition let me show you
so i'll write for animals in
i'm going to use the filter function
and inside the filter function
i'll
give
an anonymous function called lambda
i'll say lambda i
colon
i of
age
if it is divisible by 2
so i'll say age
divided by 2 equal to equal to 0
give a comma
then we will
that animal
give a colon
i'll say print
animals
so what i'm doing here is
i'm using the filter function
and passing my condition that is
if
the age of the animal is divisible by 2
then print the animal
or just print the list
rest
we don't need
all right
now let me run it
it says there's an invalid syntax let me
debug it
okay there is a spelling mistake here in
lambda this should be
mbta
okay now we'll run it there you go
so here in the list that we had created
only the age of lion and leopard were
divisible by two so 30 and 18 were
divisible by two
so python printed us only those two
elements in the list the rest it ignored
11 and 63 are not divisible by two so we
did not get dog and elephant
cool
so this is
another interesting looping technique
where you can use
filter as well as an anonymous lambda
function
all right
now in the next example we'll see how to
remove items in a list using a
while loop so so far we have been using
only for loops
now we are going to see a few examples
using while loop
okay
i am going to create a variable called
country so this variable will hold a
list of elements of the different
country names i'll say india
let's say my
second country is
canada
and let's see my third country i have is
brazil
my fourth country i have is japan
and then we have let's say israel
okay
now
i'll use a while loop so i'll say while
my list that is country
then
to remove the elements in the list i'm
going to use the pop function
so i'll say
country
dot i'll say pop and i'll pass
-1 as the parameter so that
it removes the
elements from the
end of the list if i
run it you can see here we have israel
japan brazil canada and india
now you can just
print country
you can see here since we have removed
all the elements from
my list country there is no element left
here so it gives us an empty list
cool
now let me show you how you can use
while loops in just one line
so for that i'll create a variable
called num
and i'll assign a value of 10
i'll say while
num is
greater than 0
i'll say
num
equal to
num minus 1
i'll give a
semicolon this time and then i'll say
num
let's run it you can see it here
we have printed
nine
eight seven six up to zero
so in the first iteration my num value
was 10
so 10 greater than 0 was true so we
decreased the value of num by 1 so num
became
9 and we printed 9. in the second
iteration
num which was 9
was greater than 0 then we
decreased or reduced numb by 1 again so
it became 8 then we printed it
and the loop continued till we reached
0.
cool now had this condition been
num
equal to num plus 1 or num plus equal to
1 the loop would have run for infinite
number of times
all right
now i'll
show you an example how to run an
infinite loop
so i'll say while
true
i'll create a variable called num
now this num would be
a user input a user integer input
actually
i'll pass in the message as enter an
integer
give a colon followed by a space
and then we'll say
the
product
of
i'll give a comma say num
i'll give another comma
i'll say
is
now we'll pass in our multiplication i
want to
multiply any
user given number by 5
so i'll say 5 multiplied by
num
ok
let's run it and see here enter an
integer if i say let's say 3 so 3
multiplied by 5 is 15 the product of 3
here i can change the message as
multiplied
by five
you can say is
okay
now let's run it
okay
so let's say i enter my integer as 3 i
have the message the product of 3
multiplied by 5 is 15.
let's enter another value 10
the product is 50.
let's say i have 20 the product is 100
let's see i am taking
35 multiplied by 5 is 175 so this loop
will
continue until and unless you don't
interrupt it
so i'm going to interrupt my
kernel
to stop
executing this loop
okay now we are going to explore the
enumerate function in python
but before that let me tell you what
enumerate function is
so the enumerate method or the function
in python allows us to
number list indices of the items as they
are coming out of the array python will
automatically put this indices into a
tuple
let me show you how it works
so i'll directly start with my for loop
i'll say for i in
i'll use the enumerate keyword
and within
brackets i'll pass in my
elements in the form of list
i'll say the
let's say then we have
brown
the next word i have is for
let's see then we have jumped this is
basically a sentence broken down into
different words and those words we have
put
as elements in the list
the next word i have is the
give a comma i'll say
lazy
then we have
dog
give a comma
and finally we'll have our full stop or
the period
okay then i'll give a colon
and i'll say
i
now let me run it you can see here using
the enumerate function we have
given
the
indices to the different items in my
list so it starts from zero and goes
till eight so there are total nine
elements in my list
okay
now you can see here the
result has been printed in the form of a
tuple or tuple
i'll just copy the above code and paste
it here
now i'm going to replace i with key
and
value
and
print also i'll say key comma value
let me show you the result you can see
here this time
it is no more at tuple
and here we have the indices and then we
have the
items so basically these indices have
now become the keys and
the items are the values
okay
now you can
the different elements in the form of a
sentence let me show you how to do it
i'll just paste it here
and
instead of key i'll say value
and i'll use
the end parameter in the print statement
i'll say end equal to
give us peace
let's run it you can see here
okay this should be brown fox and not
for let's run it again
so we have the sentence the brown fox
jumped over the lazy dog
okay
so similarly you can iterate through the
letters in a word or a string and print
the letters along with the indices
i'll declare a variable called company
and
this will have a value let's say simply
learn
i'll say for i comma
j
in
i'll use the
enumerate function
within brackets i'll say
company
give a colon
then
i'll say print
i comma j
let's see the result there you go so
here we have
indices assigned to the different
letters
in my word simply learn
okay
now moving ahead
so by default the index position starts
at 0 as i told you
now you can also mention the starting
index position using the start parameter
so what i'll do is
i'll copy my
above code
and paste it here now we are going to
make some changes i'll say for
i in
enumerate company
and then i'm going to give my start
parameter let's say i want to start the
index position at 10.
now if i print it
okay let's say print i
there you go here you can see
my first letter starts at index 10 then
we have 11
m at 12 p at 13 and finally we have
the last letter which is n in simply
learn is at the 20th index
cool okay
so now let's explore the zip function in
python and how you can use it to loop it
through two arrays at once
so the zip function returns a zip object
which is an iterator of tuples where the
first item in each
past iterator is paired together and
then the second item in each parse
titrator is paired together and so on
and so forth
so if the past iterators have different
lengths the iterator with the
least items decides the length of the
new iterator
let me
show you
the first example that will help you
understand how the zip function works so
i have a
list called first
and i have a
names of few
football players we have
lionel
then we have cristiano
give a comma and let's say we have
mohammed
i'll declare
another list called last
which will have
values like messi
then we have
ronaldo
basically the
surnames
of leonel christiano and mohammed then
we have salah
i'll write my for loop i'll say for i in
my zip function or the method
i'll pass in first comma last which are
my list names i'll say print
i
let me run it you can see here
using the
zip function we have
iterated through
both the list so we have lionel messi
cristiano ronaldo and then mohammad
salla
all right
now you can combine the elements of
three lists as well
so i'll just paste the code here and
we'll create another list called num
and this is going to be a list of
numbers
let's say
7
and 8 okay
now here i'll say for i
in
zip first last and num print i
if i run it
you see the result here it has zipped
only the
first three items in the
list first last and num so we have
three items printed
okay
now coming to the final section of this
demo on looping techniques in python
we'll explore about
zip underscore longest
so python's iterator tool or iter tool
is a module that provides various
functions that work on iterators to
produce complex citrators
so itreaters in python is an object that
can iterate through sequence data type
such as list tuple string and so on
so the zip underscore longest iterator
falls under terminating iterators it
prints the values of the i tables
alternatively in sequence if one of the
iterables is printed fully the remaining
values are filled with the values
assigned in the fill value parameter
so to use this
function called zip underscore longest
we need to
import zip longest from the item tools
module so i'll say from
iter tools
import
zip underscore longest
okay
then i'll
create my
first list
i'll
say let me go to the top and copy the
elements because we are going to use
these same elements again
i'll paste it here
okay
and let's say i'll give a comma and we
are going to
and i'm again going to use the
three elements okay
now i'll create another list called last
and we are going to copy the items
from the top
paste it here
and now
i'll say
for let me just scroll down
i
in
zip underscore
longest
within brackets i'll say first comma
last
we're going to print i
let me
run it and show you the result
this should be zip underscore longest
okay you can see the result
here for the first
three items it has printed lionel messi
cristiano ronaldo and mohamed salah
which you can see here but for the
last three items in the
first list it has given us
none because there were no values
now to overcome this problem you can use
a parameter called fill value
let me just copy this
and i'll paste it here
and the only change that i'm going to do
here is
i'm going to say
i'll give a comma
i'll use the parameter called fill value
equal to i'll say n a
if i run it you can see here
for the last three now we have whatever
we have
defined within field value parameter you
can change this to let's say
not defined
there you go
all right
so
these were some of the interesting
examples that we implemented using
looping techniques in python this is
going to be a completely hands-on demo
video and we'll be using the jupyter
notebook to work on the examples
so let's head over to our jupyter
notebook and begin
okay so i'm on my jupyter notebook first
of all let's rename our notebook to
looping techniques
okay
i'll just increase the
size
all right
okay
so let's see how you can arrange the
values in a list using for loops with
python sorted function
so i'll create a variable called num
and
i'll assign a list let's say it has
values 2 5
10
4
i'm taking just random values
let's say 36
50
and 49
so this is my list now i want to arrange
the
items in this list
in either ascending or descending order
so for that i can use a for loop i'll
say for i which is my iterator variable
in
and after this i'm going to use the
python sorted function
and inside the function i'll pass in my
variable which is num
then i'll give a colon and say print i
so let's
hit shift enter to run it
okay
you can see here
so python by default
has sorted the elements in the list in
ascending order so we have 2 4 5 10 10
36 49 50 and
50.
now let's learn how you can sort the
values in a list using a for loop in
descending order
so
i'll just
copy my above cell of code
we'll paste it here it will help
save us some time
so i'll say for i
in sorted
i have given my variable num
after this
i am going to pass in another parameter
called reverse
equal to
i'll say true
now reverse equal to true will make sure
python will sort the list in descending
order
if i run it
you can see the difference we have
sorted the elements in the list num in
descending order now so we have 50 50 49
36 10 5 4 and 2.
okay so this is one of the
techniques that you can use
to sort the elements in a list using a
for loop
now similarly you can also sort string
elements alphabetically in a list in
ascending or descending order
so for that i'll create a variable
called players let me just scroll down
then i'll create a list
which will have the
names of
football players let's say we have messi
then let's say we have
ronaldo
then we have salah
and then we have let's say harry
okay
i'm going to say for i
in
my function sorted
i'll say
players
i'll give a comma
and again use reverse equal to true
so
this is going to sort
the
items in my list players in descending
order of
the alphabets
then
i will give a colon and say
print i
let me run it you can see here
the names of the different football
players have been sorted in descending
order of
alphabet so we have s appearing first
then r m and h so salah ronaldo messi
and harry
alright now let's move ahead
now we are going to create a dictionary
of
key value pairs and sort it
so i'll create a dictionary called d
which will have
a few key value pairs so my first key is
f and the value is let's say 1
then my second key let's say is b
and the value is 4
give a
comma my next key is a
and the value is let's say 3
after that my next key is e
and the value is let's say 9
and finally we have our last key which
is c and the value is 2.
now to sort this dictionary i'll say for
i
in
sorted
i'm going to use the
items method
i'll say sorted d dot items
and then will print i
let me run it and show you the result
you can see it here
our dictionary has been sorted in
ascending order of the dictionary keys
so we have a b
then c there is no d here
after that we have e and then f
cool
now you can also sort the
keys and values separately let me just
copy this and i'll show you
i'll paste it here
and instead of d dot items i'll just say
d dot keys
if i run it you can see here we have
sorted only the
keys in my dictionary
now to sort the values instead of items
you can just write values
and here you can see we have
sorted the values in the dictionary d in
ascending order again so we have one two
three four and nine
all right
now we will understand how to use the
reverse function in loops to reverse the
items in a list
so i'll again
create my
list called players which will have
messy let's see again the next player is
ronaldo
and
then we have
salah and then we have harry
okay
now to
reverse the elements in this list called
players i'll say for
i in
then i'll use the reversed function and
pass in my list called players
give a colon and then say print i
let's run it here you can see
we have reversed the
elements in my list called players so we
have harry first then salah ronaldo and
messi in the end
cool
now moving ahead
we'll see how to use the filter function
in loop and filter specific elements in
a list based on some conditions now to
give the condition we'll be using an
anonymous function in python that is
often called as the lambda function
to do this
i'm going to create a list
called animals
i'll give my square brackets
and inside these square brackets
i'm going to
pass in the elements in the form of a
dictionary so to pass in a dictionary we
need to have key value peers
so my first key is name
let's see
my animal is
dogs
i'll give a comma
then my next key is the age let's say
dog's age is 11.
so this is my first
list element which has been passed in
the form of a dictionary
i'll create another curly bracket and
we'll have the same keys
this time let's say
my animal is lion
let's make it dog instead of dogs
okay
give a comma and then say
age
let's see the age of the line is 30
i'll give a comma
we'll go to the next line
and this time
we're going to have another animal
i'll say
elephant
give a comma
let's say the age is
63
i'll give a comma and then we'll have
our final
element in the list
let's say the name of the
animal is leopard
give a comma
then we'll have the age of the leopard
let's say
the age is 18
so we have our list ready
now
using a for loop
will filter
the elements in the list giving a
specific condition let me show you
so i'll write for animals in
i'm going to use the filter function
and inside the filter function
i'll give
an anonymous function called lambda
i'll say lambda i
colon
i of
age
if it is divisible by 2
so i'll say age
divided by 2 equal to equal to 0
give a comma
then we will
that animal
give a colon
i'll say print
animals
so what i am doing here is
i am using the filter function
and passing my condition that is
if
the age of the animal is divisible by 2
then print the animal
or just print the list
rest
we don't need
all right now let me run it
it says there's an
invalid syntax let me
debug it
okay there is a spelling mistake here in
lambda this should be
mbta
okay now we'll run it there you go
so here
in the list that we had created
only the age of lion and leopard were
divisible by two so 30 and 18 were
divisible by two
so python printed us only those two
elements in the list the rest it ignored
11 and 63 are not divisible by 2 so we
did not get dog and elephant
cool
so this is another interesting looping
technique where you can use
filter as well as an anonymous lambda
function
all right
now in the next example we'll see how to
remove items in a list using a while
loop so so far we have been using only
for loops
now we are going to see a few examples
using while loop
okay
i'm going to create a variable called
country so this variable will hold a
list of elements of the different
country names i'll say india
let's say my
second country is
canada
and let's say my third country i have is
brazil
my
fourth country i have is japan
and then we have let's say
israel
okay
now
i'll use a while loop so i'll say while
my list that is country
then
to remove the elements in the list i'm
going to use the pop function
so i'll say
country
dot i'll say pop and i'll pass
-1 as the parameter so that
it removes the elements
from the
end of the list if i
run it you can see here we have israel
japan brazil canada and india
now you can just
print country
you can see here
since we have removed all the elements
from
my list country there is no element left
here so it gives us an empty list
cool
now let me show you how you can use
while loops in just one line
so for that i'll create a variable
called num
and i'll assign a value of 10
i'll say while
num is
greater than
0
i'll say
num
equal to
num minus 1
i'll give a
semicolon this time and then i'll say
print num
let's run it you can see it here
we have printed
nine
eight seven six up to zero
so in the first iteration
my num value was 10
so 10 greater than 0 was true so we
decreased the value of num by 1 so num
became
9 and we printed nine in the second
iteration
num which was nine
was greater than zero then we
decreased or reduced num by one again so
it became eight then we printed it
and the loop continued till we reached 0
cool
now had this condition been
num
equal to num plus 1 or num plus equal to
1 the loop would have run for infinite
number of times
all right
now i'll
show you an example how to run an
infinite loop
so i'll say while
true
i'll create a variable called num
now this num would be
a user input a user integer input
actually
i'll pass in the message as enter an
integer
give a colon followed by a space
and then we'll say
the
product
off
i'll give a comma say num
i'll give another comma
i'll say
is
now we'll pass in our
multiplication i want to
multiply any user given number by 5
so i'll say 5 multiplied by num
okay
let's run it
and see here enter an integer if i say
let's say 3
so 3
multiplied by 5 is 15 the product of 3
here i can change the message as
multiplied
by 5
let's say is
okay
now let's run it
okay
so let's say i enter my integer as 3 i
have the message the product of 3
multiplied by 5 is 15
let's enter another value 10 the product
is 50
let's say i have 20 the product is 100
let's see i am taking
35 multiplied by 5 is 175 so this loop
will
continue until and unless you don't
interrupt it
so i'm going to interrupt my
kernel
to stop
executing this loop
okay now we are going to explore the
enumerate function in python but before
that let me tell you what enumerate
function is
so the enumerate method or the function
in python allows us to number list
indices of the items as they are coming
out of the array python will
automatically put this indices into a
tuple
let me show you how it works
so i'll directly start with my for loop
i'll say for i in
i'll use the enumerate keyword
and within
brackets i'll pass in my
elements in the form of list
i'll say the
let's say then we have
brown
the next word i have is for
let's say then we have jumped this is
basically a sentence broken down into
different words and those words we have
put
as elements in the list
the next word i have is the
give a comma i'll say
lazy
then we have
dog
give a comma
and finally we will have our full stop
or the period
okay then i'll give a colon
and i'll say
i
now let me run it
you can see here using the enumerate
function we have
given
the indices to the different items in my
list so it starts from 0 and goes till
8. so there are total 9 elements in my
list
okay
now you can see here the
result has been printed in the form of a
tuple or tuple
i'll just copy the above code and paste
it here
now i'm going to replace i with
key
and
value
and
print also i'll say key comma value
let me show you the result you can see
here this time
it is no more at tuple
and here we have the indices and then we
have the
items so basically these indices have
now become the keys and
the items are the values
okay
now you can
print the different elements in the form
of a sentence let me show you how to do
it
i'll just paste it here
and
instead of key i'll say value
and i'll use
the end parameter in the print statement
i'll say end equal to
give a space
let's run it you can see here
okay this should be brown fox and not
far let's run it again
so we have the sentence the brown fox
jumped over the lazy dog
okay
so similarly you can iterate through the
letters in a word or a string and print
the letters along with the indices
i'll declare a variable called company
and
this will have a value let's say simply
learn
i'll say for i comma
j
in
i'll use the
enumerate function
within brackets i'll say
company
give a colon
then
i'll say print
i comma j
let's see the result there you go so
here we have
indices assigned to the different
letters
in my word simply learn okay
now moving ahead
so by default the index position starts
at 0 as i told you
now you can also mention the starting
index position using the start parameter
so what i'll do is
i'll copy my
above code
and paste it here now we are going to
make some changes i'll say for
i in
enumerate company
and then i'm going to give my start
parameter let's say i want to start the
index position at 10.
now if i print it okay let's say print i
there you go here you can see
my first letter starts at index 10 then
we have 11
m at 12 p at 13 and finally we have the
last letter which is n in simply learn
is that the 20th index
cool okay
so now let's explore the zip function in
python and how you can use it to loop it
through two arrays at once
so the zip function returns a zip object
which is an iterator of tuples where the
first item in each
past iterator is paired together and
then the second item in each pass
titrator is paired together and so on
and so forth so if the past iterators
have different lengths the iterated with
the least items decides the length of
the new iterator
let me
show you
the first example that will help you
understand how the zip function works so
i have a
list called first
and i have a
names of few
football players we have
leonel
then we have cristiano
give a comma and let's say we have
mahmud
i'll declare
another list called last which will have
values like messi
then we have
ronaldo basically the
surnames
of leonel christiano and muhammad then
we have salah
i'll write my for loop i'll say for
i
in
my zip function or the method i'll pass
in first comma last which are my
list names i'll say print
i
let me run it you can see here using the
zip function we have
iterated through
both the list so we have lionel messi
cristiano ronaldo and then mohamed salah
all right
now you can combine the elements of
three lists as well so i'll just paste
the code here and we'll create another
list called num
and this is going to be a list of
numbers
let's say 7
and 8 okay
now here i'll say for i
in
zip first last and num print i
if i run it
you see the result here it has zipped
only the
first three items in the
list first last and num so we have
three items printed
okay
now coming to the final section of this
demo on looping techniques in python
we'll explore about
zip underscore longest
so python's iterator tool or iter tool
is a module that provides various
functions that work on iterators to
produce complex iterators so iterators
in python is an object that can iterate
through sequence data types such as list
tuple string and so on
so the zip underscore longest iterator
falls under terminating iterators it
prints the values of the i tables
alternatively in sequence if one of the
iterables is printed fully the remaining
values are filled with the values
assigned in the fill value parameter
so to use this
function called zip underscore longest
we need to
[Music]
import ziplongist from the item tools
module so i'll say from
either tools
import
zip underscore
longest
okay
then i'll
create my
first list
i'll say
let me go to the top and copy the
elements because we are going to use
these same elements again
i'll paste it here
okay
and let's see i'll give a comma and
we're going to
and i'm again going to use the
three elements okay
i'll create another list called last
and we're going to copy the items
from the top
paste it here
and now
i'll say
for let me just scroll down
i
in
zip underscore
longest
within brackets i'll say first comma
last
we're going to print
i
let me
run it and show you the result
this should be zip underscore longest
okay you can see the result here
for the first
three items it has printed lionel messi
cristiano ronaldo and mohamed salah
which you can see here but for the
last three items in the first list it
has given us
none because there were no values
now to overcome this problem you can use
a parameter called fill value
let me just copy this
and i'll paste it here
and the only change that i'm going to do
here is
i'm going to say
i'll give a comma
i'll use the parameter called fill value
equal to i'll say na
if i run it you can see here
for the last three now we have whatever
we have
defined within field value parameter you
can change this to let's say
not defined
there you go
all right
so
these were some of the interesting
examples that we implemented using
looping techniques in python we're going
to learn what is the control statement
and then understand the different types
of control statements in python so we
have continuous statement break
statement and past statement we are
going to
understand these in detail with hands-on
demonstrations in python on the jupiter
notebook
so what is the control statement
python programming language provides
loop control statements that can be used
to change the flow of execution and
execute a statement or group of
statements multiple times
in certain circumstances when some
particular conditions occur
we may want to exit from a loop or skip
some statements of the loop before
continuing further in the loop
so to achieve this we need the help of
control statements in python
now python provides three types of
control statements first is continue
then we have break and then we have pass
so let's look at them one by one in
detail
so the continue statement skips the
execution of the remaining statements in
the loop and proceeds with the next
titration in the loop that is it forces
the loop for the next iteration ignoring
the subsequent instructions
now on the right you can see the
flowchart of continue statement in
python so on the top we have the
test expression
now if the test expression evaluates to
false we just exit out of the loop
but if the test expression is true then
we head to our continue statement now if
this is
yes or true we again check the test
expression
if it is false or no then we execute the
statements after the continue statement
now we'll understand how the continue
statement works with the help of
examples in our demo session
so let's
see the next
statement that we have which is the
break statement
now in python the break statement is
used to terminate the loop whenever the
python interpreter or the compiler comes
across the break statement it jumps out
of the loop so it skips the remaining
code without further testing the test
expression of that loop
now here on the right you can see the
flowchart how the
break statement works in python
on the top we have the test expression
now if the
test expression evaluates to false we
exit the loop but
if it is true then we
execute the break statement
if it is yes then we
just exit the loop but if it is no then
we execute the remaining statements
after the break statement now moving to
the final control statement that we have
in python
which is the pass statement so the pass
statement in python is used as a
placeholder for future implementation of
functions loops etc
when the pass statement is executed
nothing happens actually but you avoid
getting an error when an empty code is
not allowed
it is also known as a null statement
now
let's directly jump to a jupyter
notebook where we'll explore
break continue and pass statements in
python in detail
okay so here i am on my jupyter notebook
let me first go ahead and
rename my notebook to
control statements in python
i'll click on rename
ok
now let's see how the
continue statement works in python
for that
i'm going to print
all the letters
except the letter i in the string simply
learn
so i'll give a comment as
continue
statement
okay
so i'll first write my for loop i'll say
for
letters
in my string that is
simply learn
give a colon
and then
i'll say if
letters is equal to equal to
let's say i
then i'm going to use the
continue statement
after that i'm going to say
letter
give a colon give a comma and then
we are going to print the individual
letters in the string
that is simply learn
so here
letters is actually the iterator
variable
it could be any valid
python variable
finally i am going to say print
end of execution
so here what i am doing is i want to
print all the letters except the letter
i in my string simply learn so whenever
the
i occurs in my string simply learn we'll
use the continue keyword and then move
on to the next
letter in the string simply learn if i
hit shift enter you can see the result
there you go
here you can see we have s
and the next word was i so we
skipped
that iteration and then we continued
with the next iteration so we have m
p
l and again here we
had another i present in the string so
we skipped this iteration as well and
moved on with the next so l e a r and n
finally we have printed end of execution
so this is how the continue statement
works
you can use it in a for loop or you can
use it in a while loop as well
now let's see another example where we
are going to display only odd numbers
present in a list of numbers
so
i'll say for
num which is my iterator variable i'll
say for num in
my list which
has a few numbers let's say
10
7 i have 17
let's say 42
33 19 and let's say 60.
okay
so for num in my list which is this one
i'll say if
num
mod 2 is equal to equal to 0 so if the
remainder is 0 i'll say continue
and then
we are going to
print num
so what we are doing here is for each
number
or each
item in my list which has
a list of numbers i am going to check if
that number is divisible by 2 or not if
it is divisible by 2 we are going to
skip the titration and we are going to
move ahead with the next number
so let's run it okay here you can see we
have printed or displayed all the odd
numbers that were present in my
list which is this one
so this was another simple example
of using a continue statement in python
now let's move on to the
next control statement which is break
again we are going to look at a few
examples here
all right
now the first example
we are going to see is how to break the
execution when the
number five comes up in the tuple
so for that we are going to use a while
loop now
first of all let me declare a tuple
which has let's say one two three four
five six seven and eight so numbers from
one till eight
i'm going to say
count equal to zero
and then i'm going to use a while loop
i'll say while
my count is less than 9
then i'm going to write my print
statement print
my tuple which is num
and using square brackets i'll say count
now
we're going to increment count by 1 so
i'll say
count equal to
count
plus one
next we will check if
the value of count is equal to equal to
five
i'll give a colon and then we are going
to break out of the loop
finally
we'll print
end of execution
okay
so
this code
will help break the execution when the
number five comes up in the
tuple which is num
so let's run it
okay so here you can see
as soon as the number five
occurred in the tuple
we broke out of the loop and
the break statement terminated the
execution of the loop so
you can see here we did not print 6 7
and 8 and finally we printed our last
statement which was present after the
break statement that is end of execution
okay
so i hope
this helped you understand how the break
statement works in
python
we're also going to see another example
now
so this is using a for loop
so we are going to break and terminate
the execution when the letter p occurs
in the string
simply alone
so earlier we had seen one example which
was our first
example where we saw how to use continue
statement for the same string simply
loan
this time
we are going to use the break statement
to
terminate the execution when the letter
p occurs in the string simply alone
so i'll start with a for loop i'll say
for
letters in
my string which is
simply learn
i'll give a colon
and then i'll say
my message that is
letter
give another colon i'll give a comma and
i'll put my
i treat a variable which is letters
then i'll say if
letters
equal to equal to
p will give a colon and then
i want to break out of the loop
now let me just
print it
you can see here
as soon as
the letter p occurred in the iteration
we
came out of the loop so
the break statement executed the above
lines of code and
the moment is
saw the letter p it just terminated the
loop and hence you can see we did not
print the remaining
letters in the string simply learn
okay
now moving to our
final section of the demo where we will
see how to use
pass statements in python
so the first example we are going to see
under past statement is
to check if the number is odd
so if the number is odd we are going to
pass it
else
we are going to print only the even
numbers
okay
so for that i'm going to use
a for loop but before that let me just
give a
comment i'll say pass statement
okay
so in the first example we'll check if
the number is odd then we are going to
pass it and only print the even numbers
so for that i'm going to use a for loop
i'll say for number in
range let's say i'm taking the range
between 10 and 25
give a colon i'll say if
number
mod
2
if it is not equal to
0
give a colon then we are going to
pass it
so this means if the number is odd then
just pass it
else
i'll say print
the
number
is
give a colon
a comma and then i'll pass in my
iterator variable which is number
now let's run it
okay you can see here
in the range
10 and 25 we have
excluded all the
odd numbers because we used the pass
statement so it passed printing all the
odd numbers and it just printed whatever
was there in the else part that is the
even numbers so we have 10 12 14 then we
have 20 22 and 24
so these are all the even numbers that
lie between
10 and 25
all right
now coming to the final demo
so here i'm going to write a user
defined function
to print any number other than
10.
so again we are going to use a pass
statement for this
so let me write my user defined function
i'll use the def keyword
and my function name let's say print
underscore num
then i'll pass in my parameter let's say
number
i'll say if
number is
10
then i'll use the
pass statement
otherwise i'll say else
the number
is
i'll give a comma and then i'll say
number which is there in my parameter
now let's run it
now we are going to call the function
using the
function name which is print num
if i say
print num 20
it will print my number saying the
number is 20.
let's copy this
i'll paste it here
let's say i'll say
25000
it's going to print 25000
but
if i say print num 10
you can see it here that
python has just passed it because we had
given in our condition if number is 10
then just pass it
so there was no output for 10
all right
so that brings us to the end of this
demo session on
control statements in python so we
looked at how the continue statement
works then we saw how the
break statement works we looked at two
examples one was with while loops and
the other one was with for loop and
finally we saw
two examples on past statements one was
using
for and if else and the other one was
using a user defined function and inside
that we use the file's condition
conditional statements in python perform
specific operations and take actions
depending on whether a specific boolean
constraint evaluates to true or false
conditional statements are handled by
blocks of if statements in python
now conditional statements are also
known as decision making statements
so python provides different types of
conditional statements that you can use
to make decisions
we have the simple if statement
then we have if else statement
elif statement the nested if statement
as well as nested if statement we will
learn them one by one with the help of
the syntax and code examples
so this is how the syntax of if
statement looks like so you pass in the
if condition and then we have
a set of statements inside the if
condition
so on the right side you can see the
flow diagram how the if statement gets
evaluated so first we have the test
expression
that is the if condition now if this
expression evaluates to true then we go
inside the body of the if statement so
this is basically
the body of the
if statement that contains a list of
statements or blocks of statements
now if the test expression evaluates to
false
we execute
the statements that are present after
the if condition
all right
now let me take you to my jupyter
notebook where we will
understand if statement with an example
okay so here i am on my
jupyter notebook i'll just rename this
to
conditional statements
i'll see it as demo
and we'll rename it okay
i'll just expand the
screen size
all right okay
so first of all let's
write a simple if statement
i have given a comment here
suppose we have a variable called
grade
and the value of grade is 80
then i'll write my
if statement as if
grade
is greater than equal to
50
then i'll give a
colon
then i'll write a print statement print
passed in the
exam
now this is how you write a simple if
statement so you have the if keyword
followed by
the condition so here my condition is
i'm checking whether the grade is
greater than equal to 50. now here
i've already defined my grade to 80
so this if statement or the if condition
will check whether 80 is greater than
equal to 50. now this is true
then
my print statement gets executed
let me run it and show you the result
there you go here you can see we have
our
printed message as passed in the exam
because 80 is greater than equal to 50.
now what if i change this to let's say
30
if i run this there is no output here
the reason being
30 is
greater than equal to 50 is false so
my print statement did not execute
ok
now if you want
you can
also print
another statement outside the if
condition
i'll give the message as
execute
statement
after if
now one thing to remember that
this print statement is outside the if
condition
so if i run it
only my
last print statement gets executed which
is outside the
if condition
okay
now let's write another
simple
if statement
now this time
we are not going to define the grade
value or
predefine the grade value here we are
going to take the grade value as an
input that is a user input so i'll write
grade equal to
now the way to take a user input is by
using the input function
so first of all we need to convert
our entry into an integer so i'll write
int function and inside that i'll pass
in my input function
then
i'll give my message as enter the number
all right so this statement will take
the
number from the user
now i'll write my if statement if
grade is greater than equal to
50
then
it won't give a space here
let's delete this piece
then i'll write print
you have
passed in the exam
okay
let's run it you see here
my program is asking for the
user input it says enter the number i'll
give my number as let's say 60.
if i hit enter
that gives me the result passed in the
exam
now let's run it again
this time i'm going to give as let's say
35
if i run it
there is
no output here the reason being our
grade 35 is not greater than equal to 50
so our print statement did not execute
all right okay now let me give a space
here we'll run it again and this time
we'll pass our grid as let's say
75
let me run it you can see here
it gives me the message passed in the
exam
now moving to our next statement we have
the if else statement so this is how the
syntax of if else statement looks like
so first you have the if condition
followed by a colon
if this condition evaluates to true then
we execute the list of statements that
are present inside this if condition
else
we have the else block here
if this condition returns
false then we execute the
list of else statements
so here is the
flow of how the
if statement executes the different
statements
so first we check the test expression
if that evaluates to true
then we have the body of if
and if it is false then we have the
body of else
and later
there are any statements that are
present outside the effects block will
execute those statements
now let's head over to our jupyter
notebook and we'll see
how the file statement works by example
okay
so here
i'll show you another example of using
two if statements
so i'll define my grade as 40
i'll write if
grade
is greater than equal to 50
then will
let's say
pass
then
i'll write another if statement
i'll say grade is
less than
50
then we'll print
fail
now here i'm using two if statements let
me run it
you see here
i have my result as fail the reason
being our grade 40 is less than 50 and
hence it has printed fail
now instead of using two if statements
you can use the if else statement
so in this case we'll have our if
statement checked for if grade is
greater than equal to 50
if this is true then we'll print
whatever is there inside the if
statement but in case this evaluates to
false we have another
else block that we are going to write
let me show you how to write the full
statement
so i will give a comment as
if else
okay
i'll say
grade equal to 40
then
we'll check if grade
is greater than equal to 50
pass
then
instead of using
the if statement again i'll write else
followed by a colon and then i'll write
fill
make sure this field is inside
double quotations
if i run it
it gives me the result fail the reason
being
40 is not less than
repeat 40 is not greater than equal to
50 so hence it has printed field
now instead of taking
the value as 40
we can have the
user give the input so we'll use the
input function
i'll say
enter
the
grade
let's run it again you see here my
program is asking for the user input
let's say i'll give 80
will
run it
it says pass because 80 is greater than
equal to 50 let me run it again this
time let's see i'll pass
my grid as 45
will run it
it gives us fail
all right
now moving to our next
conditional statement we have the
ellipse statement
now this is how the syntax of ellipse
statement looks like
so here first we have the if condition
now if the if condition evaluates to
true we have the body of if there is
basically a set of statements
now if the first test expression or the
if condition evaluates to false then our
alif condition gets executed now if our
l if condition is true then we have the
body of alif so this is the ellipse
statement body
finally
if the alif condition also evaluates to
false then we have the block of else
statements you can see here
we have
body of else and later if there are any
statements outside this
if alif and else block then those
statements get executed
now we'll see this with the help of
examples
okay
so here on my
cell i'll give my
comment as
if statement
okay
suppose
i have a variable called score
and
this take the value
as integer from the user so i am using
the input function
i'll say
enter
the
score
i'll give a space
then
i'll write my
if condition i'll say if score
is
let's say greater than equal to 90
give a colon
then we'll print
our message as
passed the
exam with let's say a grade
i'll just copy this statement because we
are going to
similar statement
below as well
and now i will have my
alif condition i'll write
lf
alif is actually else if
score is greater than
equal to
let's say
75
i'll give a colon
will print
past the
exam with
b
grade then i'll again have my
alif
statement i'll write if score
is greater than equal to let's say
60
will print pass the exam with
c grade
next
let's write another alif condition i'll
write lf
if score
is
greater than
this should be greater than equal to
okay
is greater than equal to
let's say
40
then we'll print past the exam with
d grade
and finally
we'll have the
else condition
i'll write
print let me just scroll down
failed
in the exam
okay
so this is how you write a
life conditional statement so first i am
taking the user input of the score then
i am checking if score is greater than
equal to 90 i am displaying my message
as pass the exam with a grade then i
have a list of
alif statements
to check for different scores
if all these evaluates to false i am
having my else statement printed
let's
run it
okay
so we'll try out different
scores
let's say
someone scored 95
if i run it
so that
candidate has passed the exam with
e-grade because
if you see the condition my score 95 is
greater than equal to 90 and hence we
have passed the exam with a grade as the
message
run it again let's say i have 80.
if i run it it says pass the exam with b
grade the reason being 80 is greater
than equal to 75 and hence we have this
message printed
let's run it again suppose someone
scored let's say 25.
if i run it
okay
it throws me an error it says name
score not defined
okay so this should be score actually
here there was a spelling mistake
i'll run it
i'll pass my score as 25
it gives me failed in the exam the
reason being my score
25 is less than equal to 40 and hence we
have failed in the exam
cool
now you can also use a for loop and then
have a list of a full block or if else
statements
let me show you how to do it
suppose i write for x in i'll use the
range function
i'll go till
10 which means from 0 to 9
then i'm checking if
my x
is
less than equal to 3
i'll print
x
is
less than or
equal to
3
okay
now
we have the
ellipse statement if l if
x greater than
5 i'll print
x
is
greater than
five
then we have the
else condition
will print let me just scroll down
i'll print x
must be
four
or
five
okay
so
here i have used a for loop and i am
[Music]
checking for each iteration from 0 to 9
and then we have a set of if elephant
else statements let's run it
there you go you can see the output here
so first
in my range i have 0
so it will check if 0 is less than equal
to 3 which is true so it has printed 0
is less than or equal to 3
so it will go till 3
and then
when 4 comes it will check if
4 is greater than 5 now this is also
false so it will skip executing the lf
statement and it will print whatever is
there in the else
block which is
four must be four or five so you can see
the message here four must be four and
five similarly for five also the same
message will be printed the reason being
5 is not greater than 5
and then for the rest of the
numbers from 6 to 9 we have
6 is greater than 5 7 is greater than 5
8 is greater than 5 and 9 is greater
than 5
all right
now moving ahead
next we have the
nested if statement so here is the
syntax of nested if so you have the if
condition and inside the if condition
you have another if condition and hence
it becomes the
nested if condition statement
and inside this condition you have the
list of statements or the blocks of
statements
so here is how the flowchart or the flow
diagram looks like
so first
we are evaluating the expression1 which
is this condition
if it is true we are going inside and
checking the second condition
if that is also true then we are running
the body of it which is this part of the
syntax
and later if there are any statements
that are present outside the if
condition we are executing those
so in case the first test expression
evaluates to false we are coming outside
and directly printing
whatever is there outside
the if condition
let's
see this with the help of an example
okay so i'll give my
comment here as nested if
cool
so first of all i'll declare a variable
called num
now this
num will have a
user input
value
so i'll write input
enter the
number
then
i'll have my first
if condition
i'll say if
number or num is less than 250
i'll give a
colon
then we'll use the print statement
num
is
smaller than
250.
i'll write my second if statement
and we'll check if num is
less than
180
and will print
num
is smaller
than
180 as well
finally i'll have my
else statement as
print number
is
greater than
180
all right let's run this
and first we'll check with the number
100
okay there you go
so here i'm checking whether 100 is less
than 250 which is true so we have
printed 100 is smaller than 250 again we
are checking if 100 is less than 180
which is true again
so we are printing 100 is smaller than
180 as well there's a spelling mistake
okay
now let's see for let's see 150
again we have 150 smaller than 250 150
also smaller than 180
let's run it this time let's say we'll
pass
300
okay you can see our
result here
300
is
less than 250 is false so we'll skip
printing this again we'll check whether
300 is less than 180
which is false again so we'll skip
printing this statement as well
we'll only have our else block printed
which is 300 is greater than 180
okay
now coming to the final section where
we'll see about nested files
so here you can see we have the syntax
for nested if else statement
so we have an outer if condition and
inside that we have another if condition
then we have
the list of
statements or the body of the if
condition
if this is false then we execute the
else part
and after that we also have an outer
else
statement
so this is how
the flow diagram looks like we'll check
for the test expression one
if that is true then we'll go inside and
see the test expression
too
and if that is true we'll execute the
body of if statement which is this part
of the syntax
then
if these are false then we'll see the
body of else one
if the second expression is false then
we go to the body of else two
and after that if there are any more
statements we'll execute them as well
all right
we'll see an example here
so i'll give my comment as
nested
if else
okay so i'll declare a variable a which
will
take a user input
of type integer
i'll say
enter
the
number
i'll write if e is less than 50
so this is my first if condition
if this is
true this should be less than 50
okay so if my first if statement is true
then we'll
check for the second if statement which
is let's say if
a
modulus 3 equal to equal to 0 which
means if the remainder of the division
is 0
then we say
a
is
divisible
by
3
and
is
less than
50.
okay
then we have our
else statement as else
my number e
is
not
divisible
by 3
but
is
less than 50.
finally
i'll have my
last
else statement
where i'll print my number e
is greater
than 50
okay so this is how you write a nested
if full statement so i am taking my
number as a user input
first i am checking that number is less
than 50
if that is true i'm again checking if
that number is divisible by 3 if it is
divisible i am printing my message as
the number e is divisible by 3 and is
less than 50.
if this is false i am saying
the number e is not divisible by 3 but
it is less than
50
else i am saying the number is greater
than 50. let's run this
and we'll try out different
examples let's say i'll say my number is
12.
my message is 12 is divisible by 3 and
is less than 50 which is
this part of the code so my number 12 is
less than 50
this is true then i'm again checking
whether 12 is divisible by 3
it evaluates to true and hence we have
this result printed
okay let's say this time i'll say 30
so i have my message 30 is divisible by
3 that is less than 50.
let's run it again and this time let's
say we'll say 72
so here i have my message 72 is greater
than 50. the reason being 72 less than
50 is false
hence this part of the code is not
executed it will directly come to the
else part
which says 72 is greater than 50.
okay
so that brings us to the end of this
demonstration on conditional statements
in python so first we learned how to
write simple if statement you saw how to
take inputs from the user
we also learnt how to write
if else statement
then you learnt about
elif statement
you also saw how to use a for loop and
inside that you can use your if
statement your lf your else
later on we saw how to write nested if
statements and finally we learnt how to
write nested efl statements
cool now let's see the agenda for today
first we will learn about the lists in
python its characteristics and explore
it in jupyter notebook then we will
learn about the pulse in python its
characteristics and we will also explore
tuples in jupyter notebook after that we
will have a look at dictionaries in
python its characteristics and will head
to jupyter notebook to understand the
dictionaries
so lets start with lists in python
imagine
you have different values
you have numbers you have strings now if
you want to group them together
you can do this job in python with the
help of lists or you have work with
arrays in any other language like c plus
or java this is the similar stuff in
here which is list
a list can be defined as a collection of
objects values or items of different
types and these collections are enclosed
within the square brackets and are
separated by commas
let's understand this with the help of
an example
we will create a list and name it as
list1 and insert the elements in square
brackets and separate them with the help
of commas
list 1 equal to square brackets one
comma adam
coma 107 comma usa
and unless we have our first element at
zeroth indexed and we have one at zero
index atom at one index 107 at second
index usa at third index
and talking about the reverse index it
starts with -1 index value we have usa
at -1 index value 107 at minus 2 index
value adam at minus 3 index value and 1
at -4 index value
we will explore the list with various
examples in jupyter notebook in a while
till then let's look at the
characteristics of lists
first the lists are ordered when we say
that lists are ordered it means that the
items have a defined order and that
order will not change if you add new
items to a list the new items will be
placed at the end of the list
second elements of the list can be
accessed by index values
third list can store various types of
elements for example numbers strings or
lists itself
fourth lists are mutable
the list is changeable meaning that we
can change add and remove items in a
list after it has been created
lists allow duplicate elements since
lists are indexed list can have items
with the same value let's have a look at
some methods of lists in python
the first one is append it adds an
element at the end of the list
for syntax we can write list1 dot append
and in round brackets we have to write
the element which we want to append
the next is insert it adds an element at
the specified position its syntax is
name of the list dot insert and in round
brackets we'll write the index at which
we want to insert the element and comma
and after data element which we want to
insert
third is extend
it adds the element of a list to the end
of the current list
its syntax is list1 dot extend and in
round brackets we will add the element
like list2
which we want to extend in the list
the next is index it returns the index
of the first element with the specified
value and its syntax is list1 dot index
and the element which you want to fetch
the index
the next is remove it removes the item
with the specified value
its syntax is
dot remove and in round brackets we
write the element which we want to
remove from the list
the next is sort
this method is used to sort the list
its syntax is list1 dot sort
the next is reverse
it reverses the order of the list
its syntax is list1 dot reverse
let's move to jupyter notebook to
explore these methods
let's start with creating a list
we'll name the list as list1
and we'll create
equal to
and we'll start with square brackets
and we'll write our first element that
would be apple
space
next element
orange
coma space the next element
banana
coma space the next element
key v
now we will get this list printed for
that we'll write the syntax
print and in round brackets we'll write
the list name that would be list1 and
run the command you can see here that
the list is printed
now let's create a different list with
some different elements
list 2
equal to
and in square brackets will write
apple
now we will insert a list
in a list
for that
we will write a list in square brackets
8 comma 4 comma
6
and coma the next element that will
write orange
the next element banana
now print this list
to print this will write print round
brackets will write list2
and run the command here we will get the
list
to print it
we can access any element in the list so
for that we will write the syntax
we want to access the second element
that will be the third element from the
list one for that we'll write the syntax
list one and in square brackets we'll
write the index two and run the command
we will get the third element from the
list one that is banana
now we will access an element from the
list2
for that we'll write the command print
list2
and in square bracket we will write 1
and in square bracket we'll write 2 and
run the command what we get is 6
so to access an element from a list that
is already inserted in and list we have
to write this syntax
so this syntax tells us that we will
first access the first index element
that is 846 the list and in that we will
access the second index value that would
be 0 1 and 2 that is 6.
so this is the syntax to access an
element in a list that is already
inserted in a list
now we'll see a reverse index order for
that we'll write the command print
list 1 and in square brackets we'll
write the index minus
and we'll run this command and we get
kv as output
now we'll see slicing in python
we can access a range of items in a list
by using
the slicing operator
now we will see an example
to see
the slicing operator work in python
for that we will write the syntax print
list1
and in square brackets we'll write 1
slicing operator 3 and run the command
what we say is orange and banana as an
output from the list 1.
when you write
one ratio 3 that is one slicing operator
3 it gives you the elements at index 1
2 and note 3
so we get the output as orange coma
banana
now we will
see another example for the slicing
operator we'll write print
list 1
and in square brackets we'll write 3
and slicing operator
run the command here we can get only tv
when we write a single number before
slicing operator
it would print the value at that index
value and all the other elements that
are present in the list but in this list
we have only kv as the last element so
it would print third index value and not
more than that
now we'll see append function for that
we'll write the syntax list1 dot
append and in round brackets we will
write the element which we want to
insert at the last of the list
we will write qova and
run it and now we will print the list to
see the result
here we can see that java is added at
the last of the list
now we'll see extend function
for that we'll write the index list one
dot
extend and in round brackets
we will write
in square brackets the particular
elements we want to insert in the list
so we will write watermelon
and the next element we want to insert
would be muskmelon
that would be in inverted commas
and we also want this list to be printed
so we'll write print list one and
execute this command
here
we can get watermelon and muskmelon add
it just after the list
just at the last elements of the list
now if you want to delete a particular
element from the list you can delete it
with the syntax
dl
space
the list name you want to delete the
element
and in square brackets you will write
the index for the element you want to
delete
we have written the fifth index value
so we'll run this command
and we'll get the list printed
we can see
that the fifth index value that is
watermelon is not there in list one it's
been deleted
now
you can also do this with another method
that is removed for that we will write
list1 dot
remove and in round brackets
we'll write the particular element we
want to remove we'll write that that is
kv
and we also want the list to be printed
so we'll write
print in round brackets list one
and run this command
we get that the key is been removed from
the list one
now
there is another method that is pop
we will write that command print
in round brackets we will write list one
dot
pop
and we'll write the index value
what we want to remove from the list
that is one
and we also want the list to be printed
so for that we'll write the command
list one
will run this command
okay we have not written the name of the
list correctly so now list one
now
so at the one index that was orange that
has been removed from the list
and now this is the new list
now
we can see another method that is clear
that removes all the elements from the
list
so
this we would apply on the list to
list2 dot
clear method
and we'll also write another command
that would be print
list 2
and execute this command we can see that
the list 2 is empty now all the elements
from the list 2 have been removed
now we'll see another method that is
reverse for that we'll write the command
list one
thought reverse
and round brackets and we also want the
list one to be printed for that we will
write the command
print list one and execute this command
here we can see that the list one has
been reversed muskmelon
guava banana apple
now
if you want a particular index element
to be accessed you can
have the syntax for that you can write
that print
list1 dot
index
and in round brackets you just need to
write the element for what you want to
get the index
and just run this command you will get
the index of the element
guava that is one
we have another method and list that is
count so count is used to give the
number of times the particular element
is present in the list so for that we
will write the syntax print
so print
and in round brackets will write the
list name list1 dot count
and round brackets will write the
particular element
for which we want to get the number of
times that has been present in the list
write musk melon
and run this command it would give us
the value 1
because it's been present in the list
for only a single time
now let's move to the tuples
so tuple tuple is almost same as list we
can have different types of values in
tuples
the difference in list
is we can change value because list is
mutable and tuple is immutable that
means you cannot change the value
a tuple can be defined as a collection
of objects values or items of different
types and these collections are enclosed
within the circle brackets and separated
by commas
let's understand this with the help of
an example we will create a tuple and
name it as tap1 and insert the elements
in round brackets and separate them with
the help of commas
so w1 equal to round brackets the first
element is one comma and the second
element is adam third element is 107 and
the fourth element is usa
now in tuples we have our first element
at zeroth index and we have one at zero
index and atom at one index and 107 at
second index and usa at third index
and for the reverse index it starts with
minus one index value we have usa at
minus one value 107 at minus two sec
index value an atom at minus three next
value and one at minus four index value
we will explore the tuples with various
examples in jupyter notebook
but till then let's look at the
characteristics of tuple
so the first is the tuples are ordered
when we say that tuples are ordered it
means that the items have a defined
order and that order will not change
elements of the tuples can be accessed
by index
double items are indexed the first item
has index 0 the second index
has
1.
third tuples can store various type of
elements that is strings arrays and many
other elements
the next is tuples are immutable tuples
are unchangeable meaning that we cannot
change add or remove items after the
tuple has been created next is tuples
allowed duplicate elements since tuples
are indexed they can have items with the
same value
let's have a look at some methods of
tuples in python
first that is index we can use the index
operator to access an item in a tuple
where the index starts from zero
its syntax is the name of the tuple dot
index and in round brackets will write
the element for which we want to access
the index
the second is slicing we can access the
range of items in a tuple by using the
slicing operator for that we'll write
the syntax top one and the range for
which we want to slice the tuple
the third is concatenation here we will
add two tuples that is we just have to
write the name of the tuples to add them
and we'll place the plus operator just
between them
the next is repetition we can have the
same item multiple times in a tuple for
that we'll just have to write the syntax
the name of the tuple
and the multiplication operator into the
times we want that
value to be present in the tuple
the next is count it returns the number
of items a specified value occurs in a
tuple
so for that we have the syntax step one
dot count and in round brackets we will
just write the element for which we want
to count the number of times that
specified value has been occurred
we also have another method that is
indexed
it searches the tuple for a specified
value and returns the position of
that where it was found
now let's move to jupiter notebook to
explore these methods so let's start
first we will comment
that would be tuples
and we'll
move to the next column and first we'll
create a tuple
for that we'll write the command to p 1
that would be the name of the tuple and
in round brackets we'll
insert the elements that would be
apple
coma
orange
coma
banana
coma
kv
now we will print this tuple
we'll just have to write print and in
round brackets the name of the topper
and run the command
will get the tuple
printed
now
if you just want to insert a single
element in a tuple for that you will
write the command tab 2
equal to in round brackets
you will write a single element that
would be apple
and run that command
the tuple has been created but this
tuple has not been considered as tuple
in python it's been considered as string
so
let's check the type of this tuple for
that we'll write print
type
and noun brackets will write the name of
the tuple we want to check
and run this command
here we can see that it is showing a
string
so a single element is been shown as
string
in python if you want that it should be
tuple
for that you just have to
insert a single comma
in the tuple and now run this command
you will get this type as tuple
now if you want to access any element in
a tupper for that you just have to write
the command print
top one
and in square brackets the index value
that is zero
and here you quote the value apple that
is at
zeroth index value in top one
now
you can also access the element in the
reverse order for that we'll write the
command print
tap one
and in square brackets we'll write the
index value -1
and run the command here we can get the
value kv from the reverse index order
now we also have the slicing operator in
tuples also
for that we'll write the command print
tap1
in square brackets
the index values
will
run this command print top1 index value
1 slicing operator 3
so it has printed orange and banana
so what does it means it prints the
index value 1 and 2 and node 3.
we also have a repetition method in
tuples for that we just have to write a
simple syntax
like print
in square brackets the element you want
to repeat
we will write the element as repeat only
and
comma we just considered as tuple
and just
after the bracket we would have to write
the multiply operator and the number of
times the element should be repeated in
the tuple
now we'll run this command
you can see that the tuple has been
created with the element repeat and the
number of times is 3 that we have
written just after the
element
so the tuple has been created now we'll
see the count method
for that we'll write the command print
the name of the tuple
dot
count
and in round brackets we'll write the
element for which we want to
know the number of times it's been
present in the tuple
and we'll execute the command
it gives us zero
as our top one
doesn't consist
guava as an element
so it gives us the count as zero
now you see
another method that would be index
for that we'll write the command
top one dot
index
and in round brackets we'll write the
element for which we want to fetch the
index of that element
banana and we'll run this command
we will get the index of the element
banana that is 2
0 1 2.
so we get the index of the element
banana
now if we want to use the append method
in tuples we have to first create the
tuple into the list for that we'll write
the command y equal to list
and in round brackets we will write
the name of the tuple
which we want to convert in the list
now we will use the append method
to the list that is why
put append
and will insert an element that would be
cova
and now
we would just assign
the y list to a variable top one
we have now converted
the y list to the tuple with this syntax
that is
tuple y and we have assigned it to the
top one value
now we'll print this tuple
and execute the command here
we can see that we have used the append
method
in the tuple
first we have changed the tuple to the
list
by this command y equal to list tab one
then we have used the append method y
dot append
and appended the element cover
then we have changed the y list to the
tuple that is stuff one equal to tuple
the name of the list and then we have
printed the tuple
we can also add two tuples by another
method
for that
we will
write another tuple that would be top
three
equal to we will insert an element that
would be
cherry
and now
we want
it to be added in top one so we'll write
top one plus equal to
top three
and now we'll
the final tuple that would be top one
and run the command here we can see that
we have added
two tuples that is tuple one and tuple
three which consists of cherry and here
we get the whole tuple as double one
now
to execute
loops in tuples we'll write the command
for that we'll write the syntax
for
space
a variable x
and
the name of the tuple
colon
and then we will print
the particular element one by one and
we'll run this command here we can see
that all the elements have been printed
from the tuple
now let's understand dictionaries in
python
in list you can fetch the elements with
the help of index numbers what if you
want to specify a different type of
index for it example if you have a list
of eight values and you want to fetch
the fifth one you will use the index but
if you have key for each element then
you can use the key to access that
element example phone book if you want
to fetch a number you will use a name
and you get a number and officially if
we talk about dictionary if you want to
understand the meaning of a word you go
to that page and you look at the word
and understand the meaning of it so this
type of concept where you have a key and
corresponding to that you have a value
we can achieve this with the help of
dictionaries
python dictionary can be defined as a
collection of objects values or items of
different types stored in key value pair
format these multiple key value pairs
created are enclosed within the curly
braces and each key is separated from
its value by the colon let's understand
this with the help of an example
dict 1 equal to curly braces the first
key is a and corresponding to that we
have value and that is separated by
colon and after the key value pair that
is separated by a comma
the next is b key and that has a
corresponding value too
after that we have inserted a comma
to separate it from other values now we
have a third key that is c and
corresponding to that we have a value 3.
let's see some characteristics of
dictionaries
the dictionaries are ordered from python
version 3.7 when we say that
dictionaries are ordered it means that
the items have a defined order and that
order will not change
second that is elements of the
dictionaries cannot be accessed by index
third dictionaries can store various
types of elements
fourth dictionaries are mutable
dictionaries are changeable meaning that
we can change add or remove items after
the dictionary has been created
fifth one is dictionaries doesn't allow
duplicate elements dictionaries cannot
have two items with the same key
now let's see some methods in
dictionaries
the first is clear method
it removes all the elements from the
dictionary and its syntax is the name of
the dictionary dot clear
the second is get
it returns the value of the specified
key
the syntax is dict1 dot key and in
square brackets we have to write the key
name
the third is keys it returns a list
containing the dictionaries key
its syntax is dict1 dot keys
the next is pop it removes the element
with the specified key its syntax is
dict1 dot pop
and in round brackets you would write
the particular key name
and the next method is pop item it
removes the last inserted key value pair
from the dictionary and its syntax is
dict1 dot pop item let's move to the
jupyter notebook and execute these
methods
first we'll add a command that would be
dictionaries
and now we'll create
our dictionary
for that we'll write the syntax name of
the dictionary
equal to
curly braces
first we will write the key value
then colon
and the value corresponding to it
will write apple
then separate it by comma
and then the second key value
colon
and
the value corresponding to that key
that would be orange
when it would be separated by comma then
we'll assign another key value that
would be 3
colon
and
the value corresponding to that would be
banana
comma
next with
the key value would be 4 colon and in
inverted commas we'll write the value
corresponding to it
and we'll print this dictionary
print text one and execute this command
here we can see that the dictionary is
printed
with one key value we have the
corresponding value apple with 2k value
we have the corresponding value orange
with 3k value as the corresponding value
banana and with 4 key value we have the
corresponding value kv
now to access a particular element
we can't do that in dictionary but we
can access a particular value with the
help of key we can do that in dictionary
for that we would write the syntax print
the name of the dictionary
and in
square brackets we'll write the key
value that would be 1 and run the
command would get the value
corresponding to the key value
that is apple that is corresponding to
the key value 1.
now
we will see a cat method in dictionary
for that we'll write the command print
name of the dictionary dot
get
and in round brackets we'll just write
the key value
and run this command we'll get the
corresponding value to the key value
that is apple
now
we will use another method that would be
pop for that we will write the command
deck 1 dot
pop
and in round brackets we'll write the
key value
for the value
we want the element to be removed from
the dictionary
we will execute this command
and we get kv as the output now if we
print the dictionary
print dict 1
we can see
that the fourth key value and the value
corresponding to that key value has been
removed by the pop method
now
we can also print the length of the
dictionary for that we'll write the
command print
len
and in
round brackets we'll write the name of
the dictionary
and just execute the command we will get
three as the output as it has been
considered one unit second unit and
third unit so the length is three
and we have
another method that is sorted for that
write the command print
sorted
and the name of the dictionary
dict 1 will execute this command
it would give us all the key values in a
sorted manner
when executed with this command
now we can see another method that is
keys for that we have to write the
command print
round brackets name of the dictionary
dot
keys
round brackets
and we'll run this command and we'll get
all the keys that are present in
dictionary
there is another method that is values
for that we'll write the command print
deck one dot
values
round brackets and we'll execute this
command
we'll get all the values that are
present in the dictionary now we'll see
another method that is update
that is used to update the particular
value corresponding to the key value or
update the dictionary with
more values to be inserted in the
dictionary
for that we'll write the command dict1
dot
update
in round brackets first we'll
write the curly braces
the key value
semicolon colon
and corresponding to that will write its
value which you want to update
watermelon
and we'll also
print the dictionary
we'll execute this command we will get
that the
second value that is watermelon that's
been updated
previously it was orange and now it's
watermelon
so it's been updated by this command and
we can also use this command to add more
elements to the dictionary
for that we'll write the syntax dict1
dot update
round brackets curly braces
and the key value colon corresponding to
that
we will write the value
muskmelon
and we will print the dictionary
and we'll execute this command
sorry we just
commented the name of the dictionary
dict one dot update
now we will execute this command
here we can see that the value has been
added to the dictionary
now we'll see another method that is pop
for that we'll write the command dict 1
pop and in round brackets the key value
for which we want the value
to be removed from the dictionary and we
will print the dictionary
and execute this command
here we can see that the second key
value has been removed from the
dictionary
and we will see another method that
would be text one
dot
pop
item and then we will print the
dictionary
and execute the command
here we can see that the pope item has
removed the last element from the
dictionary and we are left with only two
elements in the dictionary
now
we will see some loops in the dictionary
for that we'll write the command for
x
in the name of the dictionary that is
text one
colon
and then we will write print
dict one
and in square brackets
the variable x and we'll execute this
command
so with this loop we can print all the
values corresponding to the key values
in the dictionary
now to print both the
even values corresponding to it we can
run a loop for that we'll write the
command for x comma y
in
dict1
dot items
colon
x comma y
and run this command
we can get the key and the values
corresponding to it
now if you want to copy the particular
dictionary in another dictionary you can
write the command
first you will name the dictionary you
want to create and copy the elements
we will name it as my dict
equal to
now i will write the command dict 1 dot
copy
and then
we will print the new dictionary
that is
my
dict we'll run this command
okay we have
not inserted the wrong bracket here now
then this command here we can see that
we have printed the my dick dictionary
and it has the same values as dict one
now
we'll see another method
to delete
the whole dictionary
for that we'll write
text one dot
clear
it would remove all the values from the
dictionary and will also
the dictionary after that
then this command here we can see all
the elements from the dictionary have
been removed
so what is list comprehension
in python programming list comprehension
provides a short as syntax
when you want to create a new list based
on the values of an existing list
so you can build a new list with a
compact syntax based on the values of
the existing list using python
programming
now you can define a list comprehension
inside the square brackets and execute
each element using a for loop that will
iterate over all the elements
now below you can see the syntax of
writing a list comprehension i have my
variable declared as new list that will
store the list comprehension
so using square brackets i have
mentioned expression
and i'm using the for loop which is
going to iterate over all the elements
in my
old list and after that i have my if
condition
now let's look at the advantages of
using list comprehension
so it helps to accomplish your task with
fewer lines of code
now it is more time efficient compared
to running multiple loops for the same
task
and you can use iterative statements
that appear as formula now let's head
over to our jupyter notebook where we'll
learn list comprehension in detail
so i am on my jupyter notebook so let's
start with our first example
suppose you want to
find the squares of all the numbers that
are present inside a list
now let me show you the traditional way
of solving this problem
so first of all i'll declare a
list called num
and within square brackets i'll
have some numbers let's say 1 2 3 4
and now
i'll create an
empty list called sq that will
hold the
squares of my four numbers that i have
put
so i'll say for
n which is my iterator variable in
my list num i'll give a colon
and then i am going to
append the squares to my variable called
sq so i'll write sq dot
append
and to get the squares i'll say n
i'll use the
double asterisks operator to get the
squares i'll say double asterisks 2.
now
i'll just say print sq
if i run this i get the result which is
fair enough so the
squares of 1 2 3 and 4 are 1 4 9 and 16.
now
the same task you can do using
list comprehension in just
two lines
first of all i'll just declare my list
again say num
which will have the values 1 2 3 4 and
let's say 5.
now i'm going to write my list
comprehension
like this i'll say sq equal to
i'll have my expression
which is going to be n
asterisk asterisks 2
then i'll say for
my iterator variable n
in my list num that's all
so this is how you can write a
list comprehension method
and then let's print
sq
now if i run this
we get the same result you can see the
squares of 1 2 3 4 and 5 are 1 4 9 16
and 25
so
this is a simple example how you can use
list comprehension in python it is very
short and you can write
the same
task in a very compact manner as you can
see here
cool
now moving ahead let's say you wanted to
print all the letters in the word simply
don't
so for that
let me show you how to
do it in a traditional way first
so i'll create a
empty
list called let's say n underscore
letters
i'll just give square brackets so this
means
your end underscore letters is now
an empty list so i'll say for my
iterator variable letter in
my
word that is
simply learn i'll give a colon
then i'll say
n underscore
letters
dot
append
my data variable letter
now let me print
and underscore
letters
if i run this
you see here we have
printed all the
individual letters that are present in
the word simply learn
now the same task you can do using
list comprehension in just one line
so create a variable called end
underscore letters
and then i'll write my syntax as
letter for
letter in my word simply learn
and then i'll just say print and
underscore letters
run this there you go
you can use the
list comprehension technique to
implement the above task in just one
line all right
now moving ahead
we'll see how to use
a for loop
and
we are going to display
the cars
that are present in a list and have a
letter s in it
so first of all i am going to
declare a list called cars
and it will have
the names of a few cars let's say we
have
jaguar
then we have
land rover
next let's say we have
tesla
after that let's say we have
toyota
and then we have
tata
now
i'm going to create an empty list called
new list
i'll just give
square brackets
now i'll say for my i treated variable x
in
my
list cars i'll say if
we have the letter s in
x
then
i'll say
new list dot append
x
after that i'm going to say print
new list
so what
these lines of code will do is my for
loop is going to iterate through each of
the elements that are present inside the
list cars and will check if any of the
car brands have the letter s it is going
to print
that car brand
if i run it you can see here
we have tesla which has a letter s in it
the rest of the car brands don't have
the letter s and hence we have got tesla
now the same
task you can do using list comprehension
i'll just copy this line of code because
we are going to use the same car brands
and the same
list name called cars
now i'm going to write my
list comprehension technique i'll say
new list equal to
as x for x in
cars
if i'm going to use the if condition now
i'll say s
in
x
now let's go ahead and print my
new list but on this there you go you
can see that we have tesla printed
now let me just change this s to
small a or lowercase e
if i run it
you see here
all the five brands of car have the
letter
small a you can see jaguar has it land
rover also we have small a tesla has
small a
we have toyota
and tata as well now what if i change
the name of data to all upper case
so i write d8ta all in uppercase now if
i run this
there you go
since python is case sensitive
and here we are checking only for
lowercase a so we did not have
data in our result since we converted
into an upper case
all right now moving ahead
i'm going to show you how you can
filter
only those values and a list of integers
that are greater than 50.
so i'll say
new underscore list equal to
i'll say
x for x in range
i'm using the range function so i want
to print the list of integers
the first hundred integers
and i'll use my condition f
x is greater than 50
now let me go ahead and print my new
list which is new underscore list
but on this there you go
so here you can see
our
range is from
0 to 100
which means from 0
till 99 you can see it here
but we are only trying to print only
those integers that are greater than 50
so we have values from 51 till 99
suppose i'll change this to
let's say less than
45 or let's say less than 30
and if i run this
you see here you have all the integers
present between 0 till 30
cool
now moving ahead
let's see another example i am going to
use the same list which we had
declared before that is the list of car
brands
now
i am going to
all the car brands
if it is
not tesla
but if the car brand is tesla we are
going to change this to let's say audi
now let me show you how to do it using
list comprehension
i'll say
new underscore
cars
equal to
i use the square brackets i'll say x
if
x
not equal to so i'm going to use the
exclamation mark equal to
tesla
then
we should print x
else
i'm going to use the else clause as well
and say else
if the car print is
tesla then changes to audi
and i'll say for x in
cars
now let me go ahead and print new cars
there you go
so
since all these elements were not tesla
so we printed the car brands as it is so
jaguar land rover toyota and
tata
now since
we encountered one tesla here so
with the help of
list comprehension we changed tesla to
audi
cool
now moving ahead
so using function will print true for
even numbers and false for
odd numbers let me show you how to do it
so i'll create a
empty list called numbers
so this is an empty list
now i'll say for i in
range
let's say i'll set the range to 0 comma
20 i'll give a colon
i'll say
numbers dot
append
i'm going to give my condition
i
percentage 2 should be equal to equal to
0 so this means
within the range 0 to 20 i am checking
for numbers that are divisible by 2 so i
am seeing if the
reminder is 0
then i'll say
numbers
now let me run it
there you go
so there are total
20 numbers starting from 0 till 19
now
wherever the number is
even we are printing true else we are
printing false so this number starts
from the zero
place so
we have 0 as true 1 is false again 2 is
true because 2 is an even number 3 is an
odd number so we are false 4 is an even
number we have true so here
5 is an odd number so we have false so
on and so forth and the last 3
so 17 is an odd number so we are false
18 is an even number we have true and 19
again is an odd number so we have false
all right
now moving ahead
we'll see
another example
let me create
a variable called numbers
i'll say
i
percentage 2 equal to equal to 0
for
i
in
range
0 comma 21
let's print numbers and see the result
so here you can see we have the
same result this time
using
the list comprehension technique
now coming to the
final
example in this demo this time i am
going to create a four course four
matrix using the numpy library in python
and from the matrix we are going to find
the maximum element present in
each of the rows
so let me first import my
numpy library i'll say import numpy as
np
i'm going to
create a matrix
that will have random integers so i'm
using the
random module and inside that we have
the random function
i'll say
let's say
10
so i want the numbers
within 10 and i'll set the size to
4 comma 4
i'll say
print a now if i run it
you see here we have our
randomly generated 4 cross 4 matrix
where the elements lie within 0 to 10.
now from this randomly generated matrix
i am going to find the
maximum elements
so i will say max element equal to
i am going to use the list comprehension
technique so i say
max of i
for
i in
my matrix a
let's print max element
if i run it you see here the maximum
element from each of the rows so in the
first row we have eight as the maximum
element and then in the second row we
have
again eight as the maximum element
in the third row we have seven as the
maximum element and in the fourth row we
have eight again
now if i run this again my
randomly generated matrix changes
now if i run it you can see 5596
are now the maximum elements
cool
so we are going to look at what is a
function in python then we will see the
different types of python functions
then you will understand the various
advantages of using python functions and
finally we will head out to our jupyter
notebook to understand python functions
in detail with hands-on demonstrations
okay
so what is a function in python
so a function is a bunch of statements
that are defined to perform specific
operations
a function in python helps to divide
your program into smaller and modular
chunks thus allowing you to make
extensive programs more organized and
manageable it also avoids repetition and
makes the code reusable
so let's understand the types of python
functions first we have
built-in functions so these are the
functions that are built into python
so by default the inbuilt functions are
available in python then we have user
defined functions so functions defined
by users to carry out certain tasks are
called user defined functions they don't
have a fixed name
so here on this slide you can see the
different built-in python functions that
are available so you have power length
next max absolute we have print range
slice sorted round and there are many
more so these we will explore in our
demo session
so wait for a while
now
let's understand about the user defined
functions so these functions are defined
by users to perform specific tasks
and
these are the steps that you need
to create a user-defined function so
first you need to create the function
and then call the function
now moving to the
next slide so here you can see the
syntax of writing a user defined
function so we use the def keyword to
define the function followed by the
function name and within brackets you
have the parameters or the arguments of
the function
then you have the function block
and if you want to return a value from
the function you can use the return
function followed by the expression
so here is an example where we are just
printing hello python using a user
defined function and in this case my
function name is called my underscore
function if i call my underscore
function it will return me hello python
cool
okay
now let's understand the advantages of
using
python functions
so with the help of functions you can
avoid rewriting the same logic or code
again and again in a program
so in python you can call functions
anywhere multiple times in a single
program
you can also track an extensive python
program easily when it is divided into
multiple functions
and the most crucial feature or the
advantages of python functions is that
of its reusability
cool now let's head over to our jupyter
notebook and we'll explore the inbuilt
and user defined functions in detail
okay so i'm on my jupyter notebook first
i'll go ahead and
rename my
notebook as functions in
python
i click on rename
okay
first of all let me just increase the
size
okay
i'll give my comment
as built-in functions
okay
so we'll start by looking at the
absolute function in python
so absolute or abs function returns the
absolute value of a number
so i'll say let's say e equal to
i'll use the absolute
function which is represented as ebs in
python
suppose i write
abs of let's say 10.75
and if i print a
it gives me 10.75 which is fair enough
let me just copy this code i'll paste it
here
i'll say b equal to aps
this time i am going to use the
negative symbol or the negative sign
i'll say minus 10.75 and will print b
let me run it you can see here
python has automatically removed
the negative sign and it has just given
us 10.75 so this is how the absolute
function
works so abs returns the absolute value
of a number which is always positive
now let's see another inbuilt function
very popular which is called the length
function or len i just give a comment
saying len
above also let me just give a comment as
aps
okay
so later we can have a track of whatever
functions we have learnt in the demo
so the length function returns the
length of an object it could be an i
table such as a list it could be a tuple
or even a dictionary let me show you how
it works i'll say
list 1
equal to
i'll create a list within square
brackets let's say
i have
a few letters
let's say
i n then i have
d
i again
and a
so i have
all the letters in my word india now if
i say x equal to
ln of list one
then i'll print x
it gives me five because the length of
all the characters in my
list
is 5 you can count here i and dia
so there are only 5 elements and hence
it is written as 5.
now we'll explore another function which
is called as all
so the all function returns true if any
item in an iterable object is true
so i'll say
my underscore list
equal to
let's say i have
0
1 and 0
i'll say x equal to
then i'll use the all function
and inside the function i'll pass in my
list which is my underscore list
and will print x
hold on for a second and can you please
guess what this
x will be
it gives us false the reason being
we have
two false values 0 and 0 here and there
is only one true value which is 1
suppose i had 1 1 and 1
if i run this it would have given us
true because all the elements in my list
or the i triple are true
if any one of the elements is false it
will give us false
okay
now moving to our next function which is
called sum
so python sum function is used to get
the sum of numbers of an i table
let's say i have
s equal to
i'm using the function sum
and inside the sum function i'm going to
declare a list of numbers let's say we
have 20
35 and let's say
70
let me create another
list called
s1
i'll say sum
and now
let's say we'll pass in a tuple now so
i'm using another
bracket
we have let's say
7 5 and 9
now if i write
s
and let's say i want to print s1
you can see here
my sum function has
returned the sum of all the numbers in
the i treble the first one was a list
and next we have a tuple so
20 plus 35 plus 70 is 125 and then
7 plus 5 plus 9 is 21 so this is how the
sum function works
moving ahead we have the
max function next
as well as the main function
so as the name suggests the max function
will return the maximum number of an
iterable
so i'll create a variable called m1
and i'll use the max function
let's say we have a few values 7 10
3 12 61 and
40.
now let's go ahead and print m1
now if i run it
it returns me the maximum number that is
present inside my list of numbers or the
tuple that i have passed in
here you have the maximum number as 61.
now let's use the max function over a
dictionary so i'll create another
variable called m2 and i'll say
max
and inside the max function i'm going to
pass in my values in the form of a
dictionary so i'm using curly brackets
or braces
i'll say let's say 7
90 we have 3
let's say 150
67 and 44.
now let me go ahead and print m2
if i run it you can see it here it has
given us 50 which is the highest element
in my
dictionary
okay
now similarly you can use the
main function let me just copy this
and i'll paste it here
i'll say m3
instead of max function we are going to
use the main function so the mean
function will return the
minimum number in an i table
let's say i'll pass in
m3 as a
list this time and if i say print m3
it gives me three which is the lowest
number of the lowest value in my list
and similarly you can
have the lowest value printed from a
dictionary i'll just
change the variable to m4
and instead of max will use
the min function
and here also i'll use the
variable as m4
if i run it you can see here
we have printed the
minimum value in my dictionary which is
three
okay
now moving ahead
we'll explore another function called
iter
so python item function returns an
iterator for the given object so the
iter function creates an object which
can be iterated one element at a time
and the next function returns the next
item in an iterator let's use both iter
and next function in our next example
so i'll create a list called my list
and
is equal to
followed by using the iter function and
inside the item function i am going to
pass in a
list which will have
letters of india
i have n
d
i
and then i have a
now
i'll create another variable called x
and then i'll pass in the next function
and inside the next function i'll pass
in
my list and
we'll go ahead and print x
so
it will print the
first
element in my
iterable that is i here
if i copy this
and i'll
paste it here if i run it again
you can see it here the iter function
returns the
second i table which is n in my list i n
d i a
i'll paste it again if i run it
we have the
third item in the list which is d
okay
now coming to using the
power function in python so python pow
the power function returns the power of
the given numbers
let's say x raised to the power 3
so i'll
declare a variable x1 and say pow
let's say i want
the value of 3 raised to the power 3
and let's say i have another variable
called x2
i'll use the pow function and this time
i want to know what is 2
raised to power
4.
we'll go ahead and print x1 and x2
and as you guessed it 3 raised to the
power 3 or 3 cube is 27 and 2 raised to
the power 4 is 16.
cool
now coming to using the range function
so the python range function returns a
sequence of numbers starting from 0 and
increments by 1 so this is by default
and stops before the
given number
so let me show you
if i say x equal to i'll use the range
function and inside the range function
i'll have my value as 6
then i'll say for n
now here n is my iterator variable
i'll say for n in x
n
let's run it and we'll see the result
you can see here the range function has
returned us the numbers starting from
zero and it has gradually incremented
the
iterator by one so we have from zero
till five
now i'll show you another example
i want to change
the default starting value that is 0 so
i will save
x equal to
range i'm going to start from 40
till 50
with a step size of 2. so you can pass
it as the third argument so it will skip
one value and print the next value so
then i'll say for n
in
x i'll give a colon
let's print n
and we'll see the result you can see
here it starts
with 40
and has a step size of 2 so we have 40
42 44
46 and 48 cool
now let's move ahead and we'll explore
the
round function in python
so the round function rounds off a
number to the given number of digits
let's say i have x equal to i'll use the
round function
and then i'll have a decimal value let's
say
eight point six
two
four
seven five
and i want to round it to two decimal
places
let's print x
if i run it you can see here my
python has returned a rounded up value
to two decimal places so we have
8.62 and the rest it has just skipped
moving ahead we'll explore the
sorted function in python so the sorted
function returns a sorted list of the
specified iterable object you can
specify ascending or descending order
so i'll create a list called a
and we have
the elements let's say again india so i
have i
n
d i
and i have e again
if i say x equal to
sorted a and
if i print x
you can see it here python has sorted
the elements in the list in
ascending order of the
letters so we have a appearing first
then d again i and i and then finally we
have n
now
suppose you wanted to print the letters
in descending order
you can use another argument here i'll
give a comma and say
reverse
equal to
true
so this
line will ensure
my list is sorted in descending order
you can see here it has just reversed
the above result so we have n appearing
first and i i d and e
you can do the same for a list of
numbers let's say we have 12
50
38
76
let's say 27
80 and 5.
i'll say x equal to
sorted a
and will print x
if i run it you see it here we have
sorted the numbers in the list in
ascending order now
if you want to sort it in descending
order just add reverse equal to true
there you go here
my list has now been sorted in
descending order of elements
now we are going to look at the final
built-in python function which is
slice
so the slice function returns a portion
of an iterable as an object of the slice
class based on the specified range
suppose i have
a list called a
okay let's not define a list we'll
define a tuple
so this has the letters
in the word simply learn
so i have s i m
p
l
i
again l
i have e
comma i have a
then we have r and finally i have n
so these are the letters which have been
represented as a tuple
simply learn
then i'll use the slice function
and
i'll give my range as 5 and will print
a of x
let's run it you see it here
the slice function has sliced the
first
five elements in my tuple so we have s i
m p and l
cool
so we have explored
all the important
built-in python functions
now let's head over to using
defined functions or learning user
defined functions in python i'll give a
comment first user defined functions
cool
so as we had learnt in our slides
to define a user defined function we
will use the def keyword
and
a function name this should be a valid
python name so i'm using func one
followed by parentheses and then we'll
have a colon
and now we'll define the body of the
function i'll say
hello world
this is the same example that we had
seen in our
slide
now
i am going to call the function
using the function name which is
fu and c1 if i run it you can see it
here
i have my message printed hello world
so this is a very
simple
user defined function
and it does not
carry any arguments or parameters
now let me show you another
user defined function i'll say def
hello
again we are not giving any parameter
to this function or arguments to this
function
i'll say
name equal to
str this time we are going to take the
input from the user so i'm using the
input function i'll say
enter your
country name
give a
colon and a space
and then we'll say
i'll print the message
hello
followed by a space
give a plus sign
and we are going to convert our name to
string
so this is my function let me run it
now i'll call hello
it is asking me for
entering
country name i'll say japan
if i
hit enter it says hello
then
my country name which is japan so hello
japan
let me run it again this time i'll say
usa
i'll hit enter you can see here my
message is hello usa
cool
now moving ahead to our next example
where we'll see
using functions with
different parameters
so we'll start with a very simple
example
i'll say
def
i want to convert
feet to centimeter
i'll say my function name as ft
underscore 2 underscore cm
so i'll pass in a
value for feet and that feed will be
converted to centimeters
and this time inside parentheses i am
going to pass in
my parameter as f t
i'll use the formula for centimeter i'll
say
my variable centimeter equal to
feet
multiplied by
30 point
so 1 feet is actually
30.48
centimeters so centimeter becomes feet
into 30.48
then we are going to use the return
keyword and i am going to return the
output which is
centimeter
let's run it
now to call the function i'll use my
function name which is ft underscore 2
underscore cm
this is my function name
and then i'm going to pass in a
value for feet let's say i want to
convert six feet
into centimeters if i run it there you
go you can see it here
6 feet is actually
182.88 centimeters
let's see
5.8
if i run it it is
176.7
centimeters
so here you saw how to pass in arguments
to a user defined function
now again you can pass in multiple
arguments
let's say
i'm going to find the sum of two values
for that i'll create a function called
tef
my function name is add i'm going to add
two values x and y
so i'm passing in
two parameters x comma y
i'll create a variable called sum that
will store the value of x plus y
and then let's print sum
okay let me just scroll down
i'll hit shift enter to run it okay we
have created my function
that is add now let's add
40
and
50.
you have to pass in two arguments
because we have
declared
x and y in the function so it needs at
least two arguments if i run it you have
the sum of
40 and 50 which is 90.
let's say i have
minus 20 and
30 if i run it you have the result
minus 20 plus 30 is
10
all right
now similarly you can also multiply two
numbers let me just copy this
i'll
paste it here
and instead of add
i'll give my user defined function name
as
multiply
i'll say
product equal to x
asterisk y and i'll print
product let's run it
i'll call my function using the function
name multiply let's say
4
multiplied by 6
so the result is 24
cool
now moving ahead
we will explore another example let's
say i want to print the absolute value
of a number
so i am creating a function called def
my function name is absolute and i'll
pass in
one parameter which is x
i'm going to use
i felt's statement i'll say if x is
greater than or equal to 0
i'll give a colon
then i'll say return x
else
give a
colon i'll say return
minus x
i'll run it
now if i print
absolute
of let's say
56
the result is as expected since 56 is
greater than 0 we have just returned 56
let me just copy this
i'll paste it here let's say absolute of
minus 56 is again 56 because we are
returning
minus x so minus of minus 56 becomes
plus 56
now if you wanted to return minus 56
you need to
make some modifications i'll put another
minus and keep this within brackets let
me run the function again
and now if i print absolute of minus 56
you have the result as -56
okay
now let's see another example how to
find the factorial of a number using
a user defined function so we'll define
our function as def i'll use the
function name as factorial
i'm going to pass in a
parameter called x i'll say if x is
equal to equal to 0
then we'll just return x or return 1.
i'll say
else
give a colon
return
i'll say x
asterix or multiplied by i'll use the
function name factorial
i'll say x minus 1
now let's run it
i'll call my function
factorial
let's say i want to find the factorial
of 5 the result is 120 let's say the
factorial of 10 the result is
36 lakhs 28
800
cool
now let's see how you can pass in
default arguments to your function or
default parameters
okay
suppose
i have
a function defined called welcome
here i am going to pass my argument
as name
and in the argument itself i'll pass in
the value a default value let's say paul
give a colon and i'll print
hello
this would be within
quotes
and the
name
cool let me just run it
now i'm going to call the function
welcome
this time i'm not giving any value to my
function if i run it it has
automatically taken the default argument
which was paul so my message becomes
hello paul
now
let's say i'll pass in
a value
welcome
and within quotes i'll say c
now the message becomes hello ac so if
you pass in
a value to your
function welcome
explicitly it will take that value
instead of the default argument
cool
now you can also have multiple arguments
in your
function as we saw above for the
addition and multiplication
functions
i'll create a function called
message
and we'll have
the arguments as name 1 name 2 and name
3
give a colon
i'll say
a message that is
hello
and give space give a comma
we have name one
give a comma and then i'll say
comma
please
tell
give another comma
i'll have my name 2
give a comma
followed by the message that
then i have name 3
this should be a comma instead of a
period
then i'll see is
waiting
make sure this is within quotations
again
just keep a exclamation mark
okay
so i have my message let's run it
now i'll call my function
message
we need
three arguments now so i'll pass in
three names let's say my first name is
gilly my second name is rachel
and my third name is let's say shaw
i'll run it and you can see here we have
my
message printed hello followed by name
one which is kili so hello ghillie
please tell name to which is rachel so
please tell rachel
that
name three which is shaw that saw is
waiting
cool
now we'll understand about
scope of variables in a function
now your scope could be a global scope
or a local scope let's
define a function called
func
3
inside the function i am going to create
a variable called
z which has a value of 7
now i'll just print
z
and i'll call in my function
3
if i run it you have the value printed
of z that is 7 now if i want to access
my variable that is z outside the
function if i run this
it throws me an error because
this
variable z was defined locally that is
inside the function and you cannot
access z outside the function
now to overcome this issue let me just
copy this
we are going to declare z
as a global variable
so i'll have z outside the function i'll
say
z equal to 7 and then i have
my function defined i'll just change the
name of the function to
function 4
and then we'll
print z and i'll call the function
function 4
if i run it
you can see it here i have the
value of z printed that is 7. now if i
want to access z outside the function
then also it's fine because we have
defined z
outside the function that is
z is now a global variable so its scope
is throughout the function
now another thing to note here is you
can't change the value from
inside a local scope
so
if i say z equal to 7
and then i'll define my function f u n c
let's say 5
i'll give a colon and i'll say let's see
i want to alter the value of z to let's
say z plus 7
i'll print
z
and let me now call
func5
if i
run this
it throws me an error
as i said it says local variable z
referenced before assignment
so you can't change its value from
inside a local scope for that you're
going to explicitly define the variable
z as global let me show you how to do it
i've just copied this code and paste it
here
i'll say
z equal to 7
i'll define my function let's say if you
nc
6
here i'm going to say
global
c
so i've explicitly defined my z as a
global variable
now if i
call the function 6 you can see here we
have altered the value of z from 7 to z
plus 1 that is 7 plus 1 which is 8.
okay
now asterix arcs in function definitions
in python are used to pass a variable
number of arguments to a function
suppose you don't know the exact number
of arguments you need so you can use
the argument with an
asterisk symbol let me show you how to
do it
i'll say def welcome
and
here i'm going to pass in
asterix followed by the
name of my argument which is names
i'll say print
i'll print my message as hello
comma
then i'm going to say
names
the first name which is with
index value of 0
comma
followed by a space
then i have
name
one
will give a
comma followed by a space and then we'll
have
names
two
this should be names
okay let me run this
now i'll call my function welcome
now you can see here i have passed in my
argument that is names three times so
let's
call three names let's see we have steve
then we have
bill
and then we have let's see yes
now if i run this
there you go we have a message printed
hello steve bill yes
okay
now coming to the final section of our
demo
here we are going to find out the area
of a circle and a sphere so we are going
to define two functions one for circle
and another for spear
so first of all let me define the value
of pi which is 3.14
i'll start
with def
i'll give my
function name as circle area
and inside that i'll pass in my argument
that is radius
i'll give a colon and we are going to
return the area of a circle
which is pi
r square so i'll have
radius
again an asterisk symbol and then radius
so this becomes pi
into radius into radius which is pi r
square
okay now let's define another function
called def i'll say
sphere
area
i'll have my
argument as
radius
give a colon
and say
return
4 pi r square which is the area of a
sphere so i'll have 4 multiplied by pi
multiplied by
radius multiplied by radius so this
becomes 4 pi r square
now we are going to define
the main function so i'll say define
mean
where we'll just have
our print statement so i'll say print
circle
area
with
radius
15
i'll give a
comma
and say
circle area
which is my function name
and we'll pass in the value of the
radius which is 15
i'll just copy this message
and we'll print it here i'll say
spear area
with radius 15 as
i'll just change this to spear
and let's see we'll have radius for 10
instead of 15
okay
finally i'm going to call my main
function so i'll just say
main
now let's run it
okay there is one error here
this is an indentation problem now we'll
run it again there you go
so the circle area with radius 15 is
3.14 which is the pi value multiplied by
radius into radius that is 15 into 15 so
the value is 706.5
and similarly the
spear area with radius 10 is 4 into 3.14
into 10 into 10 that is
1256
all right so what is the lambda function
a lambda function
is one of the simplest ways to define a
function in python a lambda function is
an anonymous function defined without a
name and does not have the def keyword
it can accept any number of arguments
but can only have one expression
so the function is always defined using
the lambda keyword which you can see it
here
so here we have the syntax for lambda
function we use the lambda keyword
followed by the arguments and then we
have a colon after that we have the
expression that we want to evaluate
cool
now moving ahead let's
look at an example of using lambda
function in python
now
if you were to add two numbers in python
using a function you would ideally use
the
def keyword followed by the
function name and then pass in the
arguments you can see the arguments here
a and b
then
use the return statement to get the
value of the addition so we have written
a plus b
and finally you will call the add
function and pass the argument values to
get the result
now this operation can be done using the
lambda function as shown here so we have
defined a variable called add which is
equal to and then we have used the
lambda function followed by the two
parameters or arguments so here a and b
are the arguments and then i have my
expression a plus b see all this you can
do it in one line
and then to call the function you use
followed by the variable which is add
and then you have the arguments 3 comma
8 so the addition of 3 plus 8 would be
11.
now you can see that instead of using
the df keyword we have used the
lambda keyword and there is no
parenthesis required anything after the
lambda keyboard is treated as a
parameter or argument
so
we use a colon to separate parameters
and the expression in our case the
expression is a plus b
now moving ahead we look at
the pros and cons of
lambda functions so lambda functions are
suitable for simple logical operations
so when we want one expression in return
we can use the lambda function a lambda
function is used as a parameter to
different functions such as map filter
reduce we will see all this in our demo
session
now coming to the cons of using
a lambda function
so
lambda functions can only evaluate one
expression as i told you earlier
you cannot write a docs string to
explain all the inputs operations and
outputs as you would do in a normal user
defined function that uses the df
keyword
and finally lambda functions are
generally not preferred when you have to
declare a function with multiple lines
of code
now let's head over to our jupyter
notebook where we will learn about
lambda functions and how to use it in
different ways
so i'm on my jupyter notebook let me
just go ahead and we'll
rename the notebook as
lambda
functions in python
okay i'll just click on rename
cool
first of all i'll write a
general user defined function using the
def keyword let's say i want to add two
numbers
so this example we have already seen in
our slide
so the way to do is i'll use the df
keyword followed by the
function name
and then i'm giving my
arguments or the parameters
after that
let's say i want to store
the addition of a plus b in a variable
called result so i'll say result equal
to e plus b
and then
i want to return my output that is
result so i'll say return result
so this is how you will normally create
a function in python
if i run it and then
i'm going to call my function using the
function name that is add and then i'll
pass in
my parameters a and b let's say my a is
3 and b is 4.
if i run this
i will get the result 7 which is fair
enough
now if i want to
do the same operation using
a lambda function i would do something
like this let's say i'll create a
variable called add
and then i'm going to use the lambda
function
followed by the arguments
a comma p
then i'll give a colon and say a plus p
after that i'll just say add
and then pass in my parameters
3 comma 4 if i run it you have the same
result that is 7.
now let's see another example using
lambda functions to add
a number this time i am going to pass in
only one argument
so i will say add equal to
lambda
my argument is x i'll say x colon x plus
let's say i want to add x with
100
i'll say
add let's say i want to add 50 with 100
if i run it i have the result 150
all right
now in python there is no need to assign
a lambda to a variable you can directly
call it let me show you how to do it
i'll say
lambda
a comma b which are my arguments
again this time i am going to use
a multiplication
operator
since i want to do a
product of a and b
and after that
using another parenthesis you can
directly pass in the
arguments so there is
no need to explicitly assign a lambda to
a variable
so if i want to find the product of
let's say 15 comma 30
if i run it i have the result 4 t
let's change the arguments let's say i
want to find the product of 5 comma 7
the answer is 35
so this is known as an immediately
invoked function expression or iife
which is often pronounced as iffy
now you can also use keyword arguments
using lambda functions let me show you
what i mean
i will create my lambda function and
assign it to a variable called product
i'll say
lambda
let's say my arguments are x y and z
after that i'll give a colon and say
x multiplied by y multiplied by z
next i'll say print
my variable that is product
and here i am going to use keyword
arguments so i will say let's say
z equal to 5
x equal to 10
and y equal to 4.
you can see here
this need not be in an order as you have
defined the arguments
if i run this i have the result the
product of 5 multiplied by 10 multiplied
by 4 is 200.
now you can also
use default
arguments suppose i say add equal to
i'll use the lambda function
and say x comma
why i'm assigning a default
value of let's say 15 and z let's say
i'll assign a default value of 24
then i'll give my colon followed by the
expression that is x plus
y plus z
now i'll say print
add now here i'm going to only pass in
my value for x since i've already
given a default value for
argument y and z
so
my function only needs
one argument that is x so let's say i
want x to be
20.
if i run this
you see the result here so 20 plus 15
plus 24 is 59.
now you can also use the
asterix
args parameter or args
so this allows you to define as many
arguments as you want
so i'll say addition
equal to
lambda
then i'll say asterix ergs
so this will
allow us to pass in as many arguments as
you want
and i want to find these sum of
args so i'm using the inbuilt sum
function in python
now i'll say print
my variable name that is addition
and let's say i want to find the sum for
four
values or four arguments let's say 20 to
40 and let's say
50
if i run it so the value is 112 so 20
plus 2 plus 40 plus 50 is 112
cool now lambda functions are also used
with higher order functions which take
one or more functions as arguments
or return one or more functions let me
show you
so i will define a variable
called higher underscore
ord underscore f u n which stands for
function and y d stands for order
so i'll declare my lambda function
suppose the parameters are x
and then i have a
function
then followed by a colon i have
expression as x plus
function of x
now i'll say
higher underscore ord underscore
f u n
and i'll pass in my two
arguments let's say my x is 20
and for this
function
i'll have
a lambda function defined i'll say
lambda x
colon
x multiplied by x
now
let me just run this and i'll show you
the result okay so what it did was
it added
my value of x that is
20 with
function of x or f u n of x what is f u
n of x fun of x is
x multiplied by x so 20 multiplied by 20
is 400 so this becomes 400
plus x
which is 400 plus 20 hence the result is
420
so this is known as a higher order
function now let me show you another
example
let's say i want to display order event
by
taking the value of x
i'll say lambda x colon
here i am going to pass in my expression
if x
mod
2
will give a space here
i'll say and
odd
or
even
now i'll give my argument value let's
say 30
the result is even because 30 is
divisible by 2
i'll just change this to let's say 15.
if i run it the answer is odd because 15
is not divisible by 2
let's say i have 150 the answer is even
now moving ahead
so let's write a lambda function that
checks if a string is a substring of the
given string
so i'll create a variable called sub
underscore
string
now i'll assign this
variable with a lambda function i'll say
lambda
my
argument let's say string
i'll give the colon and pass in my
expression string in
let's say my string
has this message welcome to
python
functions
tutorial
okay
so we are going to check if a string
let's say in to welcome python java
anything whether it is present inside
the string which is welcome to python
functions tutorial
now let me go to the next line
i'm
going to print
sub underscore string
and let's say i want to check for my
string
let's say java
if i run it it gives me false because
the word java is not present inside my
string welcome to python functions
tutorial
suppose i write
python
now one thing to note here is
the p is small and here the p is in
capital letter
if i run it it again gives me false
because
python is case sensitive now if i make
this as capital p it will result in
true
let's say i want to say
instead of tutorial let's say i have
training
if i run it it tells me false because
the support training is not
there in the string welcome to python
functions tutorial
i'll change this to tutorial
you see here i have my result as true
all right
now let's see how to use lambda
functions using filter function so we
are going to filter a list of numbers
using a specific condition
so i'll create a
list called num
let's say it has values 40
10 40
then we have 56 27 let's say 33 15 and
70.
so this is my list
now i'm going to use
my lambda function
along with the filter function
so i will pass in my variable as greater
i'll say list
then i'm going to
pass in the filter function and inside
the filter function i'll use the lambda
function
and i'll have my
argument as num
and my expression let's say i want to
filter only those values
which are greater than 30
so i'll say num greater than 30 this is
my expression
or the condition that we want to check
i'll give a comma
and
i'll have my next argument as num
and let's go ahead and print the
variable greater
if i run this there you go you can see
here we have all the values from the
list or the numbers from the list that
are greater than 30 so we have
40 56 33 and 70. so
10
27 and 15 are
less than 30 and hence those three
values were not printed
now let's say you want to filter a list
of numbers that are divisible by four
so i'll create another list called list
one
and
let's say i'll have the
same
values in the list so i'll just copy it
and i'll paste it here
and i'll create my variable let's say
divide
i'll say divide equal to
list one
use the filter function
followed by
the lambda function
i'll say x
colon
then i'll have my expression
x
mod 4 should be equal to equal to 0
i'll give a comma and pass in my
next argument as my list 1.
now
i'm going to
say print
divide
okay
okay i'll remove the bracket here there
is no need of a bracket here cool
and we'll delete here as well
now let's run it
okay there is one error here this should
be list one
let's run it again
okay there is some error let's debug it
okay so this should be the function list
cool
there you go
so here you can see we have two numbers
40 and 56 that are divisible by 4.
the remaining
numbers are not divisible by 4 and hence
were not printed
all right
now let's go ahead and explore how you
can use the map function along with the
lambda function
so the map function accepts two
arguments a function and a list it takes
that function and applies it to every
element of the list and returns the
modified list
so we'll create a list called
list2
let's say equal to
and again we are going to have the
same values in the list as above
so i'll just
copy those values
or the numbers and i'll paste it here
okay
now
let's say
i want to find
the value of a number multiplied by 2 so
i'll say
let's say the variable name is double
the num or double the number
i'm going to use the list function
followed by the map function this time
and then we'll have our
lambda function
i'll pass in my argument as x
colon
followed by the expression
so x multiplied by 2
i'll give a comma and then we'll have
the list that is list 2
there's a spelling mistake here this
should be list 2 all right
now
i'm going to say print
double
underscore the
underscore num
make sure there is no space
in the
variable name
now if i run it
you can see here we have
multiplied every number in the list by 2
so
10 multiplied by 2 is 20
40 multiplied by 2 is 80. similarly 30
multiplied by 2 is 66
15 multiplied by 2 is 30 and again we
have
70 multiplied by 2 is 140
so this is how you can use
map function with
lambda functions
now suppose you want to find the power
of a number let's say i want to find the
power of a number raised to 3
so i'll create a list called list
3
let's say i have values 2 comma 5 comma
10 comma 6 comma 4 and then let's see we
have 12
i'll say
cube
so i want to find
the value of a number raised to the
power 3
so for that i am going to use the map
function followed by the
lambda function
i will pass in my argument x
and then
here i am going to use the inbuilt
power function in python so pow
my
argument x
and this x i want to raise it to the
power of 3
and then i'll have my
next argument which is
list underscore 3
or list 3
okay
now
let's
print the list so i'll say list of
cube
i'll run it
you can see here
so 2 raised to the power 3 or 2 cube is
8 5 cube is 125
10 cube is 1000
6 cube is 216 4 cube is 64 and 12 cube
is
1728.
now coming to the final section of the
demo where we'll see how to use
the reduced function in python along
with the lambda function and then we'll
use a lambda function within a user
defined function
so first let's look at how to use reduce
in python
so reduce applies a ruling calculation
to all items in a list you can use it to
calculate the total sum or to multiply
all the numbers together so reduce
function is a part of
func tools module so to use the
reduce function you need to import the
func tools module first so i'll say from
funk tools
import
my function that is
reduce
and then i'll say
let's say i have my list 4 this time
i'll create a list
i'm going to take the same values as
above
and i'll pass in within a list
and now
i want to find the sum of all the
numbers that are present inside this
list called list 4
so i'll do that using my reduce function
followed by the lambda function
so i'll say x
comma
and i'll give my expression as
y colon
x
plus
y
give a comma and pass in my last
argument which is my list itself which
is list four all right
and then i'll say print
sum
let's run it
there you go so 2 plus 5 plus 10 plus 6
plus 4 plus 12 is 39
so this is how you can use the
reduce function in python suppose you
wanted to find the
product of all the numbers present
inside the list so you can just
use the
asterisk instead of the addition
operator now if i run this
you have the product of all the numbers
that were present inside the list that
is list four we have twenty eight
thousand eight hundred
now
let me show you the final demo that is
using a lambda function in a user
defined function
so first of all i'll create a
user defined function to calculate the
value of a quadratic equation
so
for some of you who don't know the
formula quadratic equation it is
a x square plus b x plus c so we are
going to use that formula in our
function
and find the value using
lambda function
so i'll create a user defined function
called quadratic
and it will have
three arguments a comma b comma c
i'll say
return
and here in the return expression i am
going to pass in my lambda function i'll
say lambda
x which is my
argument i'll say x
colon
then i'll have my equation which is a
x square so i am saying a multiplied by
x
raised to the power 2 so i am using
double
astrix
plus
b
multiplied by x so this becomes ax
square plus bx
plus
i have my constant that is c
now
just go to the next line
i'm going to create a variable let's say
f
i'll have my
user defined function name quadratic
i'll pass in the values for a b and c
let's say a is 2 b is 3
and c is let's say 5
and i'll call a of 1
the value of x is 1
the value of a is 2
the value of b is 3 and the value of c
is 5
now let's run it and see the result
so
ax square plus bx plus c
for
equal to 2 b equal to 3 and c equal to
5 the result is 10.
now let's change it to let's say i want
the value of x as 2 if i run it
you have the
equation evaluated and the result is 19
all right
so let me first just give you a
brief of what are the
syntax for these functions what are the
signatures what are the input parameters
required and then we will jump into the
jupyter notebook and run some examples
so what is a map function the map
function takes another function as an
input and the second input is a sequence
of iterables it could be a list it could
be a set it could be an array or
anything you want and it returns the
output after executing the function
which you have passed as a parameter on
each of the element of that iterable so
the function could add the values could
multiply could divide or any
mathematical operation you want to do or
even you can perform certain string
operations which we will take a look in
the examples but the idea is that you
want to apply the function on each and
every iterable item individually so the
map function helps you achieve that
also in our examples we will take a look
that you don't need to explicitly define
a function you can also use lambda
functions which are inline functions uh
so you don't need to
increase the line of code you can reduce
the lines of code by just writing the
function in line and that way it will
make it more simple
[Music]
the next function which we are going to
talk about is the filter function
now what is the purpose
the purpose of the filter function is to
reduce the size of the iterables based
on the condition which you will pass to
the filter function
so syntactically it is very similar to
map function but the only difference is
that you need to pass a function which
carries a condition for example you have
a set of i tables one two three four
five six seven eight nine and you want
the function to return values which are
greater than phi
so
your filter function should have a
condition which says
that the i tables greater than 5 should
only be returned by this function
so that's why you have to make sure that
the filter function always have a
condition which is either true or false
so based on whatever condition matches
as true
the filter function will only return
those values as an output so we will
take a look
and the same
concept applies either you can make a
explicit function or you can apply
lambda function inline
the third function
which we are going to talk about is the
reduce function
the only difference between reduce
function and the other functions which
we talked about
the map and filter is that reduce
function always returns a single value
so it combines all the
values in the iterable your list your
array your set and returns a single
value so you can apply the mathematical
functions like for example you want to
add all the values in your write table
or you want to multiply so it will
multiply sequentially and give you the
output
and the same
concept applies over here you can have
lambda functions or explicit functions
also with one thing which you need to
remember is that you need to use
function tools module
to to import the reduce function
so we will take a look at that while we
will be running certain examples
okay
so here we have so we will start by
running our examples so first we will
start with map
so let's start by
defining a very simple function
which adds
two values
right and returns you the added value
right
so in the next step
we will define a
list of iterables so here we have taken
an iterable list of
four items four six eight nine numbers
now
in this step we will apply the map
function now
please notice that we are sending two
parameters to this map function one is
the
function name which is add and the
list which is numbers
okay
now i'll print
the out
but it's an object so right it's not in
a readable format so i need to convert
the out object back to a list
and now i'll be able to print
and here is my expected output so i had
four numbers in my list which is four
six eight time and the map function have
has added the numbers to itself four
plus four six plus six eight plus eight
nine plus nine and so that's how you're
getting the output as expected
[Music]
now let's take a look at another example
we're going to redefine our list
and we are going to use now a lambda
function
instead of an explicit function which is
going to multiply
the numbers in my list
within with themselves
and
we're gonna
uh print my out object
convert it back to a list
and then i'll print
converted list object
and here you go this is my output 4
multiplied by 4 6 multiplied by 6 8
multiplied by 8 and 9 multiplied by 9.
okay
so here in this example we have seen
about lambda function
now
we have been up performing mathematical
operation as i mentioned earlier we can
also perform certain string operations
so let's take an example
what i'm doing in this example is i'm
creating a map and i'm just converting
all my lowercase strings to uppercase
and i'm just printing my list now
after conversion
so such kind of uh you know
string operations are also possible
let's take another example where we are
going to print the length
of each of the
string which is there in my list
and i'm using lambda function
and here it is
so now you can see the list
the length of each and every string
variable is 3 5 6 and seven
okay
so now these were the examples of map
object
map function now we will
talk about
filter
so let's start with a simple example so
as i mentioned the filter function
should help always have a condition
so let's create a
function which has a condition saying if
a is greater than 5 then return a
it means that you need
to only return numbers which are greater
than 5 in my list
so now i'm going to call this in my
filter function
so if you see the syntax here please
notice filter you pass the fill and the
list
and then you print the out object after
converting into the list
and only the numbers which are greater
than 5 are printed
now let's take a look at
a lambda function example rather than an
explicit function
the same example but now instead i am
using a lambda function
and i am going to print it
output should be the same
okay
so the
the only change is in the syntax of the
function definition here we have
explicit function and here we have a
lambda function output is the same
now let's take an example of
a string operation string filter what
kind of string filtering we can do
so
i have an example over here
so what i'm going to do is i'm going to
have a list of string arrays
which is going to return me only those
strings which have e in them occurrence
of e
okay
so i've created a function veggies with
e
and within this list of veggies peas
garlic ginger beetroot carrot i will
only get those string variable values
which have e in it
okay so i've got the result p is ginger
and beetroot
right and garlic and carrot have been
discarded
now let's run this similar example with
lambda function
where i'm saying that okay give me those
vegetables which have r in it
so i'm just gonna run this
and print my
map
[Music]
okay and here is my expected output
garlic ginger beet root and carrot
so what have we noticed is that similar
to map filter function of course the
only difference is the function should
have a condition
which should return a true or false and
based on that the iterable list get
filters out
now
let's talk about
reduce
now as i mentioned
the first important thing is that
we
import the reduce function from function
tools okay
and then
we apply a
lambda function so we're going to start
off with just taking an example of
lambda
so here is my list of four elements 10
35 50 and 20 and i'm adding
the numbers in this list okay so so the
map function is not gonna the reduce
function is not going to add the numbers
to itself but to the subsequent number
in the list right
so what is the expected output right
expected output is 10
plus 35 45
plus 50 95 plus 20 115 so
what the reduce function has done is it
has added the numbers in the list
amongst themselves right in the orderly
fashion
now let's take another example instead
of addition we'll do a multiplication
okay
so here what we have done is we have
multiplied 9 by into 7 into 23 into 4
and we've got this answer
so this is another way of doing it
now instead of lambda function i'm just
going to show you a simple
um
adding the numbers
and define a function where you add the
first and second number
and then
you pass the function name
to reduce so custom sum and the list
similar to what we had done for map and
filter
and now you can print the result
now one thing to notice is that this
result is a single number you don't need
to convert it back to a list so you
don't need to do that transformation you
just
simply print the result
and here it is 68 3 plus 4 plus 6
plus 9 plus 34 plus 12.
so what is the class in python
a class is a virtual entity or a
blueprint for creating objects
a class in python provides a means of
bundling data and functionality together
you can think of a class
as a school so here school becomes your
class a school has attributes about the
students classrooms labs playgrounds etc
hence the school can be called a class
and classrooms labs desks playground
assembly are the attributes or objects
of a class
a class comes into existence when it is
instantiated or initiated
we can create as many objects as
possible in a class now in python a
class is created using the keyword
called class
followed by the class name the first
string inside the class is called
docstring and has a brief description of
the class
below you can see the syntax of creating
a class in python we have the class
keyword followed by the class name this
should be a valid python name and then
you have a colon
below that you have the statements that
should be present inside the class
now let's look at an example of a class
in python
so here you can see we have created a
class called student
and we have two variables the student id
and the name of the student
and after that we have created a
function using the def keyword so this
is a user defined function and the name
of the function is called display
and inside
the display function we are
giving a parameter called self so here
the self parameter refers to the
current class object and accesses the
class variables we can use anything
instead of self
but
it must be the first parameter of any
function which belongs to the class
now moving ahead
so let's look at what is an object in
python
so an object is also called an instance
of a class and the process of creating
this object is called instantiation
now you need to create an object of the
class if you want to use the class
attributes in another class or method
now the procedure to create an object is
similar to a function call so
below you can see we have created a
object called stu and we have called the
class student using parenthesis so this
is how you create a class and after that
we are displaying
the message to be printed by calling the
class name followed by the function
which is present inside the class
so this example will create a new object
instance named stu
we can access the attributes of the
objects using the object name prefix
now moving ahead
let's understand the initialization or
init method in a python class
the init method is similar to
constructors in c plus and java
all classes in python have an init
function it is always executed when the
class has been initiated you can use the
init function to assign values to object
properties or other operations that are
necessary to do when the object has been
created
so the init function is called
automatically every time the class has
been used to create a new object
so here you can see we have used
the init method we have
defined using the def keyword then we
have parameter self name and age
so we are calling
the
class using this object called s1 and
then we have passed in the values for
neiman age that is delay and his age is
27 years and after that we are printing
the age and the name as well
all right now let's get started with our
demo on
classes and objects in python on the
jupyter notebook
so i am on my jupyter notebook let me
first go ahead and
rename my notebook to classes and
objects in python
all right i'll click on rename
first of all
let me show you how to create a simple
class
so i'm creating a new class
using the class keyword so this is
the keyword class and
followed by the keyword i have my class
name called new class
one thing to note here is the
class name should always be a valid
python name
i'll give a colon and in the next line
i'll just say
x equal to 50
so this x is a variable which is present
inside my
class called new class now if i run it
i have my new class created now if you
want to display the
value of x you can just say new class
dot x now if i run this you can see here
i have my value printed which is 50.
now
we'll see another simple example to
create a class and to call that class
using
an object
so i'll say class
then i'll say
new class let's say 1
give a colon
and i'll create a variable called x
equal to 100 so my x is a variable which
is present inside new class 1 and holds
a value 100
now i'll give a comment
create object
so to create object i'll
define a variable called r let's say r
stands for result and then
i'll say
new class 1 so i'm calling my class
and then i'll say print
r which is my new object dot
x
let's run it you see here i have my
value printed of x which is 100 so this
is how you can
create or initiate a class using an
object
now let's see how you can use the self
parameter in a class
so i'll go ahead and create a class
called
student
give a colon
then i'll have some variables
or the
attributes of a student let's say the
student id is 10 and the name is
anderson
now
inside the class i'm going to
create a user defined function called
display
so i've used my df keyword followed by
the
function name that is display and inside
the display function i'll use self as my
parameter
and then i'm going to say
self dot id i'll give a comma
and i'm going to print
my name so i've written self dot name
so i'll run this
and then
we're going to create an object called s
and we'll call our class
that is student and i'll say s dot
display
now let's run it and see the result you
can see it here
we have called the
class using this object called s so it's
displaying
the id that is 10 and the name that is
anderson
cool
now we are going to see an example where
we'll pass a dog string so in the slide
we discussed that the first
string inside the class is called a dog
string and has a brief description of
the class
so let me show you an example how to
pass in a doc string
i'll create a class again let's say
called student
give a colon
and then we'll have our message
which is essentially a doc string i'll
say this is a
student class
then i'll create a variable called age
let's say the student's age is 14
and then
i'll create a user defined function
called welcome
and
have my self
parameter
after that i'll say print
my message let's say hi
comma
welcome to
section
let's say b
and then
i'll come out of the class and we are
going to
class name that is student i'll say
student dot age
and then i'll say print i'll just scroll
down
student dot
then i'm going to use the
function name that is welcome
and after that
to print the
docstring message i'm going to say
my class name that is student
dot i'm going to use underscore
underscore doc underscore underscore
now we have created a class called
student that has a variable called age
so we are going to display the age of
the student and then
we are going to display the
dot string so here we are not going to
print the message which is present
inside the function called welcome
let's run it
you can see it here
we
have the message printed so first we are
printing the age of the student and then
we have the doctrine message that is
this is a student class
all right
now let's move ahead we are going to see
how to use the
init function
in a class
so i'll say my comment init function
all right
i'll scroll down
i'll create another
class called student
this time we are going to use the init
function so i am writing def
space
underscore underscore init
underscore underscore
then we'll have our self parameter let's
say the next parameter is
name
and then we have the date of birth of
the
student
i'll say self
dot
name equal to
name
then i'll say
self dot
dob or d to birth equal to
a parameter that is
dob
and then
i'll say
my object let's say s1
i'm going to call my class student
and it will have
values of name and date of birth let's
say the name of the student is harry
and
the date of birth let's say it is
29
october
1992
all right
finally we are going to print
s1 dot name
and then i'll say print
s1 dot
date of birth
let's run it
you can see it here we have the name and
the date of birth of the student printed
cool
now you can also modify the objects that
you have created suppose i want to
change the
name from harry to virat because my
object was s1 dot name
harry i want to change this to virat let
me show you how to do it
this is very simple i'll just give a
comment that is modify objects
the way to do is you just
see the object name that is s1 followed
by the parameter that is name
equal to
let's say virat
now if i print
s1 dot name
i'll have virat instead of
harry
okay
now
if you want to delete the object
properties let's say i want to delete
one of the properties let's say i want
to delete name property of the student
to do that
i can use the del keyword followed by
the object name that is s1 and say s1
dot name
now if i print
s1 dot name it will throw an error
saying student object has no attribute
name because we are first deleting it
and then we are trying to print it and
hence
python cannot recognize this attribute
name
now you can also
delete objects that is all the objects
using the dl keyword
so this means we can delete both the
objects that we created above which is
name and date of birth
so the way to do is i'll just say dl s1
so it will delete all the objects
that is s1 in this case
i'll run this
and then let's say i want to print
s1 dot
date of birth
you see it here
python says name s1 is not defined
because we deleted it
cool
now coming to the final section of the
demo we're going to create a simple
class with init method again
so this time my class name is let's say
animal
give a colon and then i'll write my
init method using the
df keyword
i'll say self comma
name that is the name of the animal as
the parameter
i'll say self dot name equal to name
and then
i'm going to create another function
called tef
which is essentially a welcome or agreed
message
and that has a parameter that itself
i'm going to print the greet message or
the greeting
i'll say hi
my name is
give a comma and then say self dot name
now i'm going to create
my object a1 to
[Music]
initiate my class
so i'll say animal which is the class
name let's say the name of the animal is
puppy
then i'm going to say even dot
greet
i'll use parenthesis let's run it
there you go
you see here we have a message printed
hi my name is
then
using the self dot name
argument of the parameter we are passing
in the value that is poppy all right so
that was a demo session on
python classes and objects so we saw how
to create a simple class in python and
then we saw how to create
objects to
call a class
and then
we
saw how to use the self parameter
after that we saw
how to
print a message that is present in the
docstring of a class
and then we
checked a few examples on using the init
method in a class then we learned how to
modify
objects and delete objects in a class
and finally we saw another example
on init method
all right
we are going to talk about the concept
of inheritance
the types of inheritance which are
applicable so the different kind of
inheritance which we are going to talk
about are single level inheritance
multi-level hierarchical and multiple
inheritance and we are going to support
each concept with an example
before
we begin this session i just want to
highlight that inheritance is not a new
concept in any of the programming
languages
just like in python this concept is
applicable across multiple programming
languages like java c
etc
now what is inheritance inheritance
provides the reusability of a code
it allows you to inherit what you have
written in a particular class or a piece
of code and you don't need to rewrite it
you can inherit it
so that is the main purpose of
inheritance it is creating a new class
that utilizes the properties
and behavior of an existing class
so we will support this with an example
so if you take a look at the syntax the
sample syntax over here you have a base
class and you have certain attributes
functions
uh associated with the base class and
then you have a derived class in which
you extend basically you inherit the
base class and you inherit the
properties of the base class
now the new class formed is called the
derived class or the child class you can
call it anything derived child or
subclass and the existing class whose
properties are inherited is known as the
base class parent or super class these
are synonymous so any
where you hear that okay you know you're
working on a child class or derived
class you can
easily figure out that you're talking
about a derived class and whenever there
is a
reference to a parent or a super class
it means we're talking about the base
class
right
now
with this
concept with this idea let's move ahead
and
look at the different types of
inheritance which are possible in python
now here we are trying to
display pictographically
diagrammatically the different kinds of
inheritance and this will make
understanding more clear
now let's talk about first single level
inheritance you have a class a and you
have a class b so basically only till
class b only single level child is
inheriting the
attributes the properties of classes so
that is what we call as single level
inheritance
multi-level is you have
multiple level of inheritance
in for example class b here inherits
class a properties and class c inherits
class b properties so ultimately you can
see
that the the properties gets trickled
down till class c right so that is the
example of a multi-level
right
next is hierarchical in which
two classes are inheriting from a single
class class b
is also inediting from class a and class
c is also inheriting from class a so
both class b and class c
are kind of siblings to the parent class
a right
multiple inheritance it means that a
child class in is inheriting properties
from two parent classes
so in this example the class c is
inherited the properties of class a also
and class b also
so we will be looking at these examples
when we will be running in python
now let's
take this example with a real world
object right let's first try to
give you a
view of how
we are going what we want to explain in
the inheritance with real world objects
right now here we are taking an example
of a black and white tv and a color tv
now single level inheritance in this
type of inheritance there is only one
single derived class from a single base
class as i mentioned earlier so for
example you can assume there is a class
called black and white tv and what are
the attributes of a simple black and
white tb it has a regulator it has a
sound adjustment
now
there is a child class called color tv
which inherits the basic attributes of
course a color tv also has a regulator
or sound adjustments but
additionally on top of it it also
provides new features like color picture
and cable connection so now
what do you understand by this is that
the child inherits the basic properties
from the print class
but it also adds on the new additional
features so the color tv does not need
to rewrite
or
the
functionality of a regulator and the
sound adjustment it has inherited
multi-level
very similar to single level but now we
are adding more features
so like in the previous example color tv
inherited the features of black from
black and white tv
now we move a step ahead now there is
another classification another
advancement of wi-fi led tv so that has
also narrated the features from color tv
right so it's a multi-level inheritance
so just to reiterate the black and white
tv had channel regulator dish antenna
the color tv added additional features
of color picture quality and cable
connection
and the wi-fi enabled tv added the new
smart features to the tv which it
inherited from the color tv
multiple inheritance now in multiple
inheritance the derived class is
inherited from more than one base class
right so now for example over here you
have a class called android which is an
android operating system based class
and one is the wi-fi led class which has
the wi-fi features of like sound picture
wi-fi enablement and if you combine all
these features and bring it into another
child class that class is the smart tv
class which has the features of android
and the features of wi-fi led tv and
then you call it as a smart tv it has
all the android applications it has the
wi-fi features and etc so this is the
example of multiple inheritance getting
the best of
all the parents
here kill
if more than one class is inherited from
the base class right so now if we just
tweak our prior example and you know
just
rephrase it what we are saying is now
from the black and white tv you can also
make a color tv you can also make a
smart tv or you can also make a wi-fi
led tv right so there is no restriction
as such so basically the color tv is
also inheriting the features of a black
and white tv smart tv is also inheriting
the features
of a black and white tv and the wi-fi
led tv also is narrating the features
from black and white tv so it's a very
typical example of a hierarchical in
inheritance
so now let's
quickly look at the examples
okay so let's start off
with a
very simple
single
level inheritance
let's make a class
and
create a function
called speak
and print something
okay
now let's make another class
so what we did was we created a class
called homo sapiens and in the and now
we are creating a clause called man
which inherits
uh the attributes
of homo sapiens
and we say
create a function which is specific
to man so homo sapiens has a function
which called speak and man has a
function called talk
and let's print it
now
let's create an object of
man
now what does this signify
the man
class is also inheriting whatever is
there in homo sapiens so man can even
talk and he can even speak right
so what we are going to do is
first we are going to execute the
function
speak
so the
the base class function got called speak
and it is printing homo sapiens speaking
and also we can call the child function
man talking okay so so if you see
this is the basic difference which we
want to highlight
that
just you have created the object only
for the child class not the parent so
now making by making the object of the
child class
you can invoke the parent class function
as well as the child because the child
has inherited the parent features
now
let's take an example of
multi-level
so we will
continue from our previous example we
will create class homo sapiens
define in
functions peak
and
now we will make another class
man
now we are saying
man can
walk
so we are saying man walking
now this is the third level this is the
multi-level
man child
and
we are saying that a man child can eat
so ultimately the man child can speak
can walk can eat all three operations
can be performed
so we are gonna make a object of
man-child
and now
python will allow us
invoke
walk function
speak function
and
eat function
so this is a typical example of
multi-level
hierarchy
now
moving to our
next
type of inheritance which is the
multiple inheritance
where
the child
is deriving
attributes properties from
two parents
so we will now create a class called
calculation1
in our example
and let's make a function
sum
and
it will return
calculation x plus y
second
calculation two
and
let's create
operation subtraction
and it will return x minus y
okay
now
we will create
the derived class which is inheriting
both calculation one and calculation two
and
let's create its own
function called
multiplication
okay so derived class now has a sum
function subtraction function and
multiplication okay
so let's create an object for derived
and
now let's
invoke the relevant functions
so sum
120
subtraction
it should say minus 40
and
multiplication
so if you see
it's it's different from multi-level
it's multiple it means that the child
class
has inherited from two parents it's
relevant functions right
and that's how we are able to call them
in the derived class
now let's take another type hierarchical
inheritance
okay
so in hierarchy
inheritance
let's go back to our example of
first we have the black and white tv and
we will create a function called
antenna
print channels are telecasted through
antenna
then we will create
color tv
and
we will define its own function called
cable connection plus it has an edited
the function called antenna from black
and white tv
here it is okay
now we are going to create another
class called as
wi-fi led tv which is also in editing
from black and white
now in this we are defining bluetooth
tethering function
[Applause]
okay
and let's make another smart tv
okay and then we are gonna
you can watch
android applications on otp platform
right so this is the
class of smart tv
okay so what we have done eventually
over here is we have created a black and
white tv
color tv also inherits from black and
white tv wi-fi led also in edits from
black and white tv smart tv also edits
from black and white tv
okay now
let's try to
create the
relevant objects
we will first create an object of color
tv
then we will create
wi-fi led tv
and then we will create
smart tv
okay
now we will have the relevant functions
available to invoke
so both all the child all the children
objects now will have an antenna
function a1
a2
and a3
all three are having the antenna
function so we can just try to print it
okay
and then
we can invoke the relevant
child functions
a1
cable connection
bluetooth triggering
and
android applications
so if you see this is an example of
hierarchy
you have color wi-fi led in smart tv all
inheriting the black and white tv
features
and its own
its own feature
[Music]
okay
now along with this concept let me just
also introduce
some relevant concepts which are
applicable
along with
the inheritance concept which will be
helpful
i also want to show you
the example of
init function init function
is a constructor in python language
and it is called by default whenever you
instantiate an object
so let me give you an example over here
so here you have a
class person
and you have
we are just defining the init function
the constructor
okay and
we are just
defining certain attributes
instantiating certain attributes in the
person first name and the last name
and another function which i am calling
is the
print name
and i'll print the name it's a
straightforward function
okay so what i'm doing is i am creating
a child class now
called as student
which is inherited
uh the features attributes of the person
base class
and
i'm also making a constructor for
student
and from student i am invoking the
constructor of the person class right
so now if you see i'm going to make an
object of student
and initialize it with
the self the first name and the last
name
and in eventually
the
parent class init function is being
called first name and the last name and
this function diff print name it will
print james anderson right as i have
already initiated the
parameters
okay so if you see now what have i done
i have
the attribute values in the parent class
are getting printed
by invoking the constructor of the child
class
so what happened when you invoke student
by default this init function got
invoked the parameters of james and
anderson got passed then from person you
invoke the constructor in it and here
now the first name and last name got
initialized
and then it got printed
so this is the basic feature of a init
function
now
like the way i have called person dot
init over here i i can also make a call
to super there is a keyword called super
keyword
so let's just take an example of super
keyword
okay
let me have my child class like the
previous one parent class the person
class
and
i'll have to just make a change in my
student class
in the init function instead of parent
dot init i will call
super dot in it
this is the keyword
super function
which will always
invoke the parent class
gives you the handle to the parent class
and then you can invoke the relevant
method
and
the invocation methodology will be the
same
and you can
check the output it's going to be the
same but it's that the syntax is
different there is another keyword which
is available for you to invoke the
parent so you don't need to know the
class
of the parent you can just make a call
to the super
now let's also take a look at another
utility utility function called is
subclass right
so
what we are going to do is
we are going to create a function
calculation one
calculation two okay so we have created
two classes calculation one calculation
two independent classes no one
inheriting each other
now we are going to create a derived
class
now this is the example what we had done
earlier very similar to multiple
inheritance so we are just actually
creating a
multiple inheritance
example
okay so you have a derived class which
has multiple inheritance from
calculation 1 and calculation 2
summation multiplication and divide
relevant functions are there
now we will check
which class is a sub class of which one
right
so let's create an object of derived
now what we want to print is that
whether derived
is a sub class of calculation 2
and it should return true
and let's see
another is calculation 1 a sub class of
calculation 2 it should return false
right because these two are independent
classes so is subclass is another
function which is available in python
which helps you
decide you know you can check whether
which is a derived class and which is
not a derived class
next
let's take an example of another
function called is instance okay
will take the same
set of functions
create an object of derived
and check
whether
the object d is of which
is it is it of a
instance of class derived or not it's
true so instead of derived if i make it
as calculation 2 for example now if i
say c
equal to
calculation 1
and say c
is instance of derived
it should say false but if i say
calculation 1
it should say true
and if i say
calculation 2
should say false because
calculation class is an independent
class d is a derived class from
calculation one and calculation two so
basically d is in is instance of both
calculation one calculation two so it
will always return true
we are going to talk about what is a
python nitrater what are iterables right
what are the iterable objects
how an iterator works
and then we will also discuss about how
to throw a stop iteration exception
basically when you reach the end of a
list
then you can throw a stop iteration
exception and we will see that with an
example
now what is a python iterator
python nitrator is an object that can
traverse through iterable objects in
python like lists tuples dictionaries
sets
and returns data one element at a time
so basically you can traverse through
these layers one at a time and then you
can use it as per your custom
requirement but iterator as an object is
available to you is a tool available to
you in order to traverse through each
and every element
now
they are implemented within for loops
comprehensions generators in python
implicitly they are not visible up front
but they are hidden in plain sight so
basically when you're using loops when
you're using generators comprehensions
implicitly python is actually converting
them in the back end in an iterator
object and giving you the results
now what are iterables on which you can
iterate
lists tuples dictionaries sets as i
mentioned are all iterables or iterable
objects other than these you can't
perform any iteration if you have not
created an object of list tuple or
dictionary or said then of course your
right variable will not be of any use
and
these objects internally possess an item
method iter method which is used to get
an iterator a handle to an iterator and
then you can start looping it or you can
start accessing the elements of the
iterator
now how iterator works
python iterator implements internally
these two methods which you are seeing
on the screen underscore underscore item
underscore underscore brackets and
underscore underscore next underscore
underscore bracket
now these two methods are implicitly
implemented by python for any internal
implicit iterator
object
but if you have to write your own custom
iterator
then you need to override these methods
and i'll show you in my examples in
jupiter notebook
the iterator object is initialized using
the either method so basically whenever
you have to create an iterator object
you need to initialize it with iter and
then use next method in order to
traverse through it
now stop iteration exception so as i
mentioned when we reach the end of an
iterable right like suppose you have a
list or a set which has a length of four
when you have ended the fourth element
and you're trying to access something
beyond fourth element which is fifth
then of course you can implicitly raise
a stop titration exception or python
will throw it so we will see that with
an example but you will get a stop
iteration exception
now so to prevent in order to uh handle
it
or
manage it in your course we use top
iteration statement to raise an error
you can raise your customer error so you
can catch this exception
and then raise your custom error in the
underscore underscore next method
so now let's uh support everything with
our examples
let's start with a very basic
example of an iterator now let me create
a list
with just four
numbers
and
as i said i'm gonna initialize my
iterator with item method so now i have
created a list and now i am initializing
it with item okay
now using next i'm gonna print my first
element four okay so it means the iter
internally has given me handle to the
first element
and now as many times i move print next
i am moving to the next element
so now i'm also going to show you a
different syntax this is a syntax but
the output will be same it's a different
syntax to invoke underscore next so it's
output is going to be same but the
syntax is only the difference over here
so you're going to get access to the
next element
and then
my fourth element just 33 now i have
traversed through all my four elements
now what will happen if i again do next
i have ended i am at the end of my list
so i will get an exception of stop ice
iteration right and this is thrown by
python
now let's take another interesting
example if i want to perform iteration
on
strings
so i have created a variable and i have
initialized it with geeks
and now i have created an iterator on
top of this uh
string variable and i'm going to
traverse it
till the time i end reach the end of my
string
so let me
hydrate it and i'm going to iterate till
the time i get the stop iteration
exception
so also i might explaining here how to
cleanly handle the exception
accept
and then break if i get the exception
i'll break out of this program
and here you get the result
all the letters of my string geeks has
been printed individually
and i think it's a very important
example interesting example that how a
string has been converted now
point to be noted over here is
that python has internally invoked
underscore underscore iter and
underscore underscore next methods which
it has implicitly implemented for string
iterators so you don't need to do
anything
now let's take another example to how to
traverse through a list
using for
loop
so i'm going to leave for object in list
and just print the list this is without
a nitrater i'm just printing my list so
i'm just trying to show the difference
that if you use a nitrater or you do not
but how you can access the
elements in the list
now let's take an example
of how i can write my own custom
iterator
okay so i'm
creating a class where i'm overriding
the init method
basically initializing in is a
initialization
of my class where i'm gonna initialize a
variable max with zero
and then
i am overriding this is the most
important point over here i am
overriding i t e r method
and then
i am writing another overriding the
underscore underscore next method
where i am adding
6 to my number and then
incrementing my loop
so that
i
can move further
so in this underscore next method i am
just
moving beyond adding 6 and till the time
i reach the max variable so when i'll
invoke my class
i am passing 9 so it means that i should
not
go beyond
10 basically i should start my iteration
from 6 and will not go beyond 10 9 plus
1
so i should get numbers which are
between 6 to 10 as per my expectation
now before we diagnose the output most
important point is that how you have
converted your class to an iterator over
here
you in order to invoke make an a class
in nitrater it is mandatory you override
it ar and next method which you have
done over here
so now let's print
okay
so six so my
number started with 0 initialized with 0
and i added
six to eight so my first result is six
and now if i keep printing i will get
one value incremented
seven
eight
nine
and
ten right so this is the expected output
right
now
another example on the same lines i'm
gonna print the first 20 numbers using
my iterator
so i am
going to overwrite the iter method and
underscore underscore next method my
numbers now in this
underscore underscore next method i'm
just incrementing my number y one
not by six and i'm gonna stop at the
limit 20
so like i showed in my previous example
i'm gonna initialize first my class
and then
uh initialize my iterator and just then
gonna run a for loop on it
and here is the response output i have
printed the first 20 numbers because i
have created this limit
so i am initializing with one
and going till the max 20 number
but the point is it's not the output
which is more important over here the
most important concept over here is that
you have created your own iterator and
leveraged it we will talk about what is
a generator in python we will talk about
the advantages of using generators
and the utility of the next function
which
allows us to
operate with generators and print the
values within the generator so we will
see these
all these concepts with an example
now what is a generator in python
python generators lets you create your
own iterator functions that return the
traversal object with a sequence of
values
so basically even with iterators you can
only work on list tuples or sets but
with generators you can convert your
functions into iterator functions itself
and we will see that when we will be
working on a jupiter notebook
now another important feature in a
generator function is that a yield
statement is used rather than a return
statement
so basically
the return statement terminates a
function entirely if you use it within
the function and you know basically
return from the statement while the
yield statement pauses the function
there it is
and holding all its states all its
variables the values in the variables
and then continue
thereafter on the successive calls
so basically in a generator function you
use yield functions and i will talk
about the utility of this yield
statement within the generator function
how it helps in generating pipeline
but just to hold a thought over here and
understand the concept the yield
statement basically holds
the processing of the function at that
point and if you make an invocation of
that generator function again it starts
from there itself where you left it
as compared to return statement return
is a general exit
if you make an invocation of the return
statement from a function it will
restart again from the beginning if you
invoke it the next time and that's the
basic difference
so what are the advantages of using
generators it's very easy to implement
the code syntactically it's very simple
within the few line of codes you are
able to achieve
the
you know functions and able to implement
the logic
you can generate infinite sequence you
don't need to provide the range values
the starting and ending you can generate
an infinite value and i'll show you that
with an example
and
generators are very memory efficient
they are the most memory efficient ways
of processing huge data sets
they process the data incrementally and
do not allocate memory to all the
results at the same time they do that
incrementally
they really come in handy when
implementing data science pipelines for
huge data sets in a resource constraint
environment where you have
you know constraint on the ram and the
other resources of the hardware
now another biggest advantage is
pipelining with generators
generator pipelines are a great way to
break apart complex processing into
smaller pieces when processing list of
items so basically you can
break your complex code into smaller
pieces and then
invoke them as a generator
recursively and we will see that how
but basically you are making the complex
code look simple and making it invoke in
a pipeline fashion
now the another most important function
in order to deal and operate with the
generator is the next function
the next function is used to retrieve
elements from a generator object and
then print it so that's how you
basically
interact with your generate function
you cannot do that until unless you
don't use next function
so now let's quickly
jump to our examples
which we are going to support for each
of these concepts now let's start by
basically
creating our
first
generator function
i am going to
create a variable n initialize it with
one
and i'm gonna do a print
this is just for my
logging
and showing on the console that where we
have reached
and then i'm gonna say yield n
okay
so now here we are not exiting the a
function we are just
saying
that just uh you know this is the point
if you invoke the function again the
function will start from this point on
now here
you will
increment
and again if this is the second
checkpoint in the code
and similarly
this is the we're gonna have a last
checkpoint in the code
now in order to
create my generator now this is the
my generator initialization my gel
now if i
use the next function and invoke my
generator
now
my
generator has
been executed till this point right
n equal to 1
now if i
make a second invocation
now it has moved ahead and printed the
second so it is behaving like a loop it
is now behaving like a loop it is
behaving like a nitrater uh but i have
not created any list i have not created
any tuple but i am basically traversing
through the variables through the
sequence of the variables within my
generator
and if i again
print it
this is my last this is printed at the
last so all the
checkpoints within my generator have
been executed
now
the same example which i have over here
let me
call it in a loop
okay
so what i'm gonna do is i'm gonna
remove these invocations and just
replace it
with a loop call right so this generator
functions remain as is
now instead of writing my next
function
three times
i am going to just invoke my generator
in the for loop and this will get
invoked the number of times i have yield
in my generator
and my output should be
the you know these logs which i have
created
and of course the variables
yeah so see now what has happened is
now the output is all these three print
commands have been executed plus the
variable values of n has been imprinted
at each at point 1
2 and 3.
so when i initialize my item variable
during the for loop this item consists
of the variable values which are there
in my generator
now i'm going to show you
example of if i use a return statement
in my generator
so i am going to create another
generator
and
provide a value
now in during this in middle of this
generator i am just invoking return
and then i am
printing my second checkpoint
and then the
last checkpoint
now
i'm gonna initialize my generator
now if i invoke
my
first element of the generator i'll get
it there's no problem because i printed
the first item i called the value of my
yield and then i return
but now if i invoke my second element in
the generator
but before invoking second i have
already given the return statement
my
generator will exit
and i'll get the stop iteration error
now this is a python generated
exception which is denoting that you
have you cannot move beyond the first
item because you have returned from the
generator over here
so that's the difference if you just
remove this comment this out
and then run it
you will get your second item so it's
not the code exits if you write return
over here so i hope you are able to
understand the difference
now let's take another example now here
we are going to create a list and how
a implicit list like the way legacy way
we have been creating in python
differentiates like the way we are
creating a generator
so what i am doing is i am creating a
list with random numbers
and then another list in which i am just
square rooting
the numbers in that list
and similarly i am also creating a
generator
which
i am expecting the same output in the
new list as the generator
but i am going to show you different
ways
of traversing the generator as compared
to a list
now if you see this list underscore if i
just make a print call to this list
it's going to straightforwardly
uh square root
uh the numbers and give me the output
four nine sixty four and hundred
but if i print the generator
i will not get the expected output what
i'm expecting i will just get the
generator object which is not what i
desire so basically you can't just print
the generator like the list
you have to
either use the next or you have to use
the for loop which i had shown earlier
and print each and every item within the
generator
now this is the output which i was
expecting i was expecting the
line by line
output of each and every element in my
generator
4 9 64 100
okay
now this for loop is taking care that it
is not exceeding
the number of items the length of the
items in the generator so this is
automatically taken care by this syntax
but if you don't take care of it then
you will get an exception let me show
you another example
if i create a list
and now i'm creating a generator
which is square
of square of all my elements
so now one by one
instead of the loop i'm one by one
printing the output
second output
third element output
fourth element output
okay i have four now if i try to again
i'm exceeding the
length of
the
list i'm going to get an exception stop
iteration exception because i'm
exceeding the length right either i use
the 4
or if i'm using individual print and
next function then i have to take care
that okay how many elements are there in
the list and i cannot exceed beyond that
else the python will
raise an exception
okay
now i'll show another example of
highlighting the difference between next
and
the for loop printing i'm gonna create a
uh generator for 2 to the power n
so i'm initializing n with 0
and then just
raising it
2 to the power n
now here i'm initializing my generator
and printing it
and i am getting the expected output as
2 raised to the power 0 1 okay
now another way of doing this job is
i
loop over this
and i get the same output so if you see
it's only
i do not have only one element so either
you use for loop or you print using next
the output is going to be
same
now another important concept which i
talked about
if you want to print infinite infinite
numbers
so
or you want to do some infinite
calculations
i'm going to use print in
all
even numbers
so i'm gonna
write an
generator
which is gonna print
infinite number of even numbers
so i've created a generator
and now i'm going to invoke this
and mind you i have to kill this job
because it's going to keep running
it's going to keep running keep running
because it's constantly generating the
numbers even number
so i would have to stop this
but if you see
otherwise this is not possible in any
for loop the basic for loop you have to
give a range start and end of the length
but using a generator you can do
infinite
looping
right because here i have to kill this
job i have to do a keyboard interrupt
now i'm going to show you an example of
how you can use generators for creating
a pipeline
so i'm going to take example of
fibonacci series
create an example of fibonacci two
variables initialized with zero and one
and now
i'm going to
write the logic of fibonacci adding the
two numbers
to itself
subsequently and i'm gonna add yield
now this is my generator this is my one
generator
and i'm gonna create second generator of
square
so i'm gonna
show you in excel
what logic i'm going to apply and what
will be my expected output
so i am now squaring the numbers which
i'll get out as an output of
fibonacci
okay
now
i'm gonna
i'm creating a pipeline
like this
first i'm gonna generate fibonacci
series for the first 10 numbers
then
i'm gonna find the square of each of the
fibonacci numbers and add it
so if you see this
representation in excel
i'm going to generate
and these are the two variables which
i've already initialized x and y and
from
here on these
10
are my first 10 fibonacci numbers
i'm going to find calculate the square
of these numbers 1 4 9 25
and till 55 the square of 3 0 2 5 and
then add these numbers and i should get
the output of 4895 so if you see one
function generator second generator and
the third calculation now this hole
has been done in one single line of code
you have generated created two
generators
and just invoked them in a single line
pipeline
so entire looping
and you know
you don't have to write the looping
operators the for loop and you do not
worry about writing all that complex
logic it is all encapsulated within this
now let me run and i'm going to expect
this output 4895
and here is my output right so in the
hindsight what python has done is it has
generated these fibonacci numbers found
the square of these numbers and then
added it in single line
and now this is the convenience
simplicity which i was talking about
earlier
now let's take another example of
fibonacci
i'm going to create a generator again
initializing a and b with 0 1
[Music]
and this time i'm taking an example of
printing the fibonacci in two different
ways
okay
i'm gonna print
the first
five fibonacci series number
the first way i'm gonna do is i'm gonna
the next function five times because i'm
generating five
so let me run this
these are the first five fibonacci
number zero one one two and 3
and i am also going to use a
loop
in order to print
so now in the loop i am invoking the 5
fibonacci numbers
and run it
so either you can
make individual five individual calls or
you can use the for loop but the output
is the
same
and you are using a generator so what is
string formatting in python formatting a
string is something you will do all the
time when you are coding in python
string formatting also known as string
interpolation is the process of
inserting a custom string or variable in
predefined text
the string formatting methods
format the given string into a more
precise output in python
so it is the process of infusing things
in the string dynamically and presenting
the string now let's look at the
different types of string formatting in
python first one we have is using the
modulo operator so python uses c
formatting style string formatting to
create new formatted strings python does
that with the help of the modulo or the
percentage sign
this is the old way of formatting
strings this approach was more often
used in python 2.
so let's head out to our jupyter
notebook and see how this works
so this is my jupiter notebook that i'm
going to use for our demo
so let's start with our first example
that is formatting a string using the
modulo operator first i'll create a
variable called name let's see the name
is sean and i have another variable
which has the age of sean let's say 32
now i can create a variable called
string
equal to i'll say
hi
then use the modulo operator followed by
s
and i'll give an exclamation mark
give a space
i'll say
percentage
name
and then let's
print the string
if i run this
we have the output hi
shawn so what i did here was
we have defined the variables that we
want to format into the strings
then we have created the string with the
placeholders for the variables so this
is a placeholder
now the percentage s format specified
here tells python to substitute the
value of the
name
so hence we have high sean printed
now let's see another example
this time i'll directly use a print
statement
i'll say
i like
to
then i'll say percentage s
or modulo s
chocolate
ice creams i'll give a full stop
and then using my modular operator i'll
pass in my value that is eat so here
percentage s will be replaced by the
value 8.
now if i run this you have the message
here i like to eat chocolate ice creams
now you can also add
multiple strings at a time and you can
use variables to insert objects in the
string let's see one more example i'll
say string equal to say percentage s
is i'll say
percentage d
years old
then
i'll give a percentage symbol and say
name comma age
and let's
print the string
if i run this
you see here above we had defined the
variables name in age to be sean and 32
so here percentage s is for name so so
on
is
percentage d
is for age so son is
32 years old
so in this example percentage d format
specifier tells python where to
substitute the value for h
and it is represented as a string so
percentage s
is used to inject strings similarly
percentage d is used to inject integers
so here 32 is an integer and you can
also use percentage f for floating point
values and you can also use percentage b
for binary format
all right
now let's see another example
let's say i have a variable called x
which has
a value dance
i'll say
nancy
can
i'll say percentage s and
percentage
s
2
after this
we'll
specify
the parameters let's say x and
sing
if i run this
you have the output nancy can
so here percentage s is for x which
means dance so nancy can dance and
percentage s is for the second
parameter which is saying so my result
becomes nancy can dance and sing two
now similarly we can have another
example using
percentage f let's say i'll say print
the
value of
e
is
now i'll specify my format which is
going to be let's say percentage 5 dot
2 f close the quotation and then i'll
pass in my value for e let's say
2 4 5 5
3
dot
i am just taking random floating values
7 1 8 2 8 1. if i run this you see the
result my value for e is
24553.72
now let me tell you what
5
dot 2f means so here 5
would be the minimum number of digits to
be present in the string these might be
padded with white spaces if the whole
number doesn't have this many digits
and here 2f represents
how many digits are to be displayed
after the decimal point so after the
decimal point we wanted only two digits
so we have rounded it up and the value
is
seven two
all right
so coming to the
next type of string formatting in python
we have formatting with the format
string method
so python string dot format method was
introduced in version 2.6 now there are
two ways to do it one is using
positional arguments and the other is
using keyword arguments
so let's head over to our jupyter
notebook and we'll explore a few
examples on this before that let me just
give a
few comments so the first one we saw was
using
modulo operator now the second one is
not an operator this time we are going
to use the
format method cool
if getting your learning started is half
the battle what if you could do that for
free visit skill up by simply learn
click on the link in the description to
know more
so under format method we'll use empty
placeholder and replace them with a
string value
so
i'll write a print statement
let's say my
message is
welcome to now i'm creating
one placeholder which is empty you can
see here and let's say after that i have
tutorials
i'll give a full stop and then we are
going to use the
format method and inside the format
method we are going to
pass in the value let's say simply loan
so this
simply learned value will be substituted
in this empty placeholder
let's run it you can see the result we
have
welcome to simply learn python tutorial
so
this empty placeholder was replaced with
a string value that is simply alone
cool
now moving to the
next example so we'll be using index or
positional arguments inside the
placeholder
let me create a variable called s1
and i'll type in a message let's say
my message is let's
i'm using my first placeholder and i'm
giving a
position or an index
now in python you must be aware that the
index starts from zero
so i've used curly braces and passed in
zero i'll create another placeholder and
this time i'll put
index as one let's say my message
continues like this with
simply loan
and then
we'll use the format method
and we'll pass in the values for these
two placeholders
it should be width
let's say my value for the
zeroth index is
learn
and
my value for the first index is upscale
i'll go ahead and
print s1 and you can see the output
let's learn and up skill with simply
learn so here the zeroth and the first
index were replaced by learn and upscale
respectively so this is how you can use
index or positional arguments inside the
placeholders now you can also
add index numbers into the placeholders
to reorder values now this will affect
the order in which the method replaces
the placeholders let me show you so i'll
create a print statement
so let me create my first empty
placeholder and then i'll continue with
my message
let's say called
then i'll have my second placeholder
and i'll continue with my message to
inform that
then i'll have my third placeholder
will be absent
okay
now
let's use the dot
format method and we'll
have the values for all the three
placeholders let's see my first value is
luke
my second value is
dina and my third value is
john now if i print okay there is some
error here okay
there has to be another
bracket here now if i run it you can see
the message here
so the first placeholder was for luke so
luke called
dyna which is my second value to inform
that
my third placeholders value that john
will be absent
cool
now you can
add index numbers into the placeholders
to reorder the values now let me show
you how to do it i'll just
copy this
message and i'll print it here
and here i can now pass in my
index values let's say i'll add 2
0 and 1
so here
luke is for 0
dyna is for 1 and john is for second
index value now if i run it
now you can see the
difference in my message so here first
two comes which means john called
the value at zeroth index which is luke
so john called luke to inform that dinah
will be absent
all right
now let's see one more example this time
we'll be using name or keyword arguments
inside the placeholder in the earlier
examples we saw how to use positional
arguments
or index
this time we are going to use name or
keyword arguments inside the
placeholders
so i'll create
another variable called s2
and
i'll have my message let's see v
in my first placeholder i'll have the
keyboard as a then i'll have my keyword
as b my message will continue
i'll have my third place holder as c
with
simply loan
and then we'll use the
format
method
and then i'm going to pass in my
keyword arguments
so here we have to assign the value for
a b and c
so let's see the value of a is
loan
for b
let's say it
is upscale
and for c
let's say the value is grow
now
we need to
print s2
if i run it you see the message here we
have v learn
upscale and grow with simply loan
let's say we'll replace v with
let's
so the
message is more appropriate
so now you can see let's learn upscale
and grow with simply loan so this is how
you can use
keyword or name arguments inside
placeholders in the format method
cool
now let's look at the
third method we have
formatting with
string literals called f strings so
strings in python are usually enclosed
within double quotes or single quotes to
create f strings you only need to add an
f before the opening codes of our string
so this type of formatting is also
called as a formatted string literal
now when you
use f strings you need to display
variables so for that you need to
specify the names of the variables
inside a set of curly braces and at
runtime all variable names will be
replaced with their respective values
so let's go to our jupyter notebook and
we'll see a few examples
all right
now let me give a comment as
f
strings
okay
so
let's see our first example under
f strings
type
so i'll say
tutorial
equal to python
then i'll have another variable called
subject which has the
value
programming
next we have place equal to
simply loan
and then i am going to
use a print statement
and then i'll use my
f
keyword for f strings
and i'll say my
message as let's
learn
then using
curly braces i'll pass in my
variable name that i have defined here
first is tutorial then we have subject
from then i'll have the place
let's give a full stop and we'll close
the double quotes and let's run it so
here you can see we have our message
let's learn python programming from
simply learn so here tutorial and
subject
were replaced by python and programming
because we have defined tutorial as
python and subject as programming and
please we have a simply learn and hence
my message is let's learn python
programming from simply loan so
this is how you can use f strings so
when using f strings to display
variables you only need to specify the
names of the variables inside a set of
curly braces
you can also evaluate expressions
with python f strings let's see a simple
multiplication i'll create a variable
called n1 which has a value of 60 let's
say n2
has a value of 12
and i'll use my print statement
i'll give my
f keyword for f strings
i'll say the
product of
then i'll create my placeholders n1
and
next placeholder is n2 is
and then using
curly braces i'll do a multiplication
operation
that is n1 multiplied by n2
i'll close my
double quotes let's run it
so you can see here the product of 60
and 12 is
720 let's say i'll make it 10 and
40 if i run it the product is 400
cool
now you can
also use
f strings
in conditional statements
so you can use conditionals in python f
strings let's see
an example i'll create a variable called
num which will have a value let's say 55
then
i'm going to use a print statement
and use my f letter
and then i'll pass in my message is
number even
give a question mark then using
curly braces i'll have my placeholder as
true if
num
modulo 2 equal to equal to 0
else
display false
i close my double quotes
now let's print it
you see here is
number even the output is false because
55 is not even let's say i'll make it 50
and if i run it as number even the value
is true because 50 is divisible by 2 and
hence it is even all right
now coming to the
final type of
stream formatting in python we have
formatting with string template class
now template strings are provided as a
class within the string module of the
python library it is imported as a
module and the
dot substitute method is used to replace
the placeholders
now the format uses placeholder names
formed by the dollar symbol with valid
python identifiers
let's go to our jupyter notebook and
we'll see two examples on this all right
so this is the final section of our demo
let me give my comment as
template
string
okay
so first and foremost we need to import
the template
module so i'll say from string import
template now let me first run it i'll
create two variables the first variable
is a1 which has a value of
python
the next variable is a2 let's see the
value is
simply loan
then i'll create another variable called
n
which will have my template
function
and inside the function will pass in our
message
let's say
hello
welcome
to
now i'll use my
dollar sign and say let's say
n1
programming
so this is my template that i'm creating
by
again i'll say dollar
and two
give a full stop
now i'll say print
and
dot we are going to use the
substitute method so i'll say
substitute
n
1 equal to a1 so here i'm going to
replace n1 with the value of a1
and then i'll say
replace n2 with a2 all right
let's run it and we'll see the
result there you go so here my
output
becomes hello welcome to
now n1 we have replaced with a1 so hello
welcome to
python programming by n2
now n2 we have referred to a2 so
it becomes simply loan so hello welcome
to python programming by simply loan
now let's
see our last demo
again this is on
template
strings
so i'll create a variable called stu
name which essentially stands for
student name let's say the name of the
student is
johnson
then i'll create a variable called s and
i'll use the
template
function or the method i'll say hey
using the dollar sign i'll say
name
how are
you how are you followed by a question
mark
i'll say s dot
substitute
i want to substitute
this dollar name with sdu underscore
name
which has johnson
now if i print it
you can see the message here hey johnson
how are you
great
so
that brings us to the end of our demo
session on string formatting in python
what is scope in python
so scope in python is the area of the
region of a program where you can access
variables functions and objects declared
the scope defines the accessibility of
the python object so the objects cannot
be accessed from anywhere in the program
variables are not visible to the entire
code so their visibility can be
restricted
now scope verifies which variable to be
accessed
a variable declared inside a function
belongs to the local scope of that
function and can only be used inside
that function
now whenever you use a name such as a
variable name or a function name python
will search through different scope
levels or namespaces to determine
whether the name exists or not
so python resolves names using the legb
rule the legb stands for local
enclosed global and built-in scope
now talking about local scope
the variables which are defined in the
function are called local scope of the
variable so these variables are defined
in the function's body
now talking about
enclosing scope
now this scope only exists for nested
functions if the local scope is an inner
or nested function then the enclosing
scope is the scope of the outer or
enclosing function
coming to
global scope
the variable which can be accessed from
anywhere in the program is known as the
global scope
such variables can be read inside or
outside the function
now the global scope is often
implemented when we want to use the same
variable name in the rest of the program
coming to the
final rule which is b that is built in
scope so if a variable is not defined in
local enclosed or global scope then
python looks for it in the built-in
scope now this scope contains names such
as keywords functions exceptions and
other attributes that are built into
python
now if you define the same variable name
inside and outside of a function python
will treat them as separate variables so
two separate variables one available in
the global scope that is outside the
function and the other available in the
local slope that is inside the function
now let's head over to our jupyter
notebook and we'll try
scopes in python with hands-on
demonstrations
all right so i'm on my jupiter notebook
let's start with our
examples first we'll look at
local scope in python
for that i'm going to create a function
called
fun
and
inside the function i'll create a
variable called
s which
holds let's say
an object called
simply loan
and then
am going to
the variable that is s
now in this case i have defined my
variable
inside the function so this becomes
accessible only
inside the function
now if i call the function using the
function name that is fun
and if we run it you can see we have the
message printed that is simply loan
now
we'll see another example
so suppose
we'll try to access it outside the
function it will throw an error so i'll
just give a comment try
to access
it
outside the function
all right
so again i'll create
a function called let's say
fun 1
i'll give a colon and here i'll say
let's say
s1 equal to
simply loan
and now
i'll give a comment here print s1
then i'll call my function fu n1
and
i'll try to
the variable s1
outside the function
so here s1
has a local scope since it is defined
inside the function but i am trying to
access the variable outside the function
let's run it
you can see the error here name s1 not
defined now
if i give a
comment
and run this
you see there is no message and let me
just remove this comment and print it
you can see we have the
s1 variable message printed that is
simply known so this is how the
local scope of a function works
now let's see an example of
enclosed scope which is
function
inside another function
so i'll create a function
let's say func
and
i'll use the variable this time s2 equal
to
simply loan
and then
inside the func function i will define
another function let's say
i n f u nc which basically stands for
inside function
and then here i'll say print s
s2
and
we'll call the
inner function that is in
fu and c
and then i'll call the outer function
let's run it
and see the
result
you can see here we have the
message printed
simply learn i'll just
edit this message let's say
welcome to simply loan
now if i run this
you can see we have updated the message
here
now
for the enclosed scope you need to
define an outer function including the
inner function like we
did here
and you can also comment out the local
variable of the inner function and refer
to the variable using the
non-local keyword let me show you an
example around this
suppose i have a
global variable called msg
i'll say this is a
global
scope
message
after that
i'll create a function so i'll define a
function called
outer
and
i'll use the same variable name that is
msg
and my message would be this is
an
outer variable
after that
i am going to define another function
called
inner
and
this will have
the same variable that is msg and my
message would be
inner
message
variable
now as i mentioned before i need to
comment out the
local variable of the inner function so
i'll just
comment this out
and then
i'm going to say
non-local which is the keyboard
so i'm referring to the variable using
the non-local keyword
i'll say non-local
variable name that is msg
and now
i'll
print msg
will come out of the function and we'll
call it
inner
after that we'll call the
outer function
and then i'm going to print i'll just
scroll this down
and we'll say msg
so here what we are doing is so this is
an example of an enclosed scope so where
we have
defined the outer function enclosing the
inner function and we have commented out
the local variable of the inner function
and we are referring to the variable
using the non-local keyword now let's
run it you see here i have my
two
print statements working here the first
one is this is an outer variable you can
see here and then i have print msg so
this is a global scope message cool
now
we'll see an example of how the global
scope works though we have already seen
an example above so this was an example
of a global
scope
now we'll see a few more examples around
global scope again
suppose i have a variable called s3
equal to i'll say
simply loan
and then i'll declare a function
f u n c
one
i give a colon and then say
s s3
now i'll call the function fu and c1
and we'll print it
s3
if i run it you can see here i have
simply learned printed twice so i have
used the same variable name s3
inside the function so
this simply learn is for the
local scope s3 that is this one and
outside the
function we have printed s3 again so
simply learn twice
all right
now let me show you another example
about using the
global scope
create a variable msg1
let's say my message is
welcome to
simply loan
python
programming
i'll define the function f unc 2 i'll
give a colon
and i'll use the same variable that i
used
or declared above that is msg1
i'll say this is the
inner msg1 variable
then i am going to print msg1
after that i will call my function func2
and i'll print
msg1
if i run this
you can see i have the two messages
printed first is this is the inner msg1
variable and the second print statement
will print the
global variable
message that is welcome to simply known
python programming
cool
now you can also
use the global keyword inside the
function to convert a local scope into
global scope
now
i'll just give a comment using
global keyword
so i'll define my function func let's
say 3
i'll give a colon
and using the global keyword
i'll say
s
and i'll say s equal to
simply loan
now let me
call fu and c3
and will print s outside the function
now one thing to remember here
my variable has been declared inside the
function
but since before declaring the variable
i have assigned the global keyword to s
so this now becomes a
global scope variable so you can access
it outside the function as well now if i
run it you can see it here i have my
message printed
simply learn if i say hello you can see
it hello printed
cool
now
we'll see another example of using the
global scope
let's say i have a variable called e1
which is
india
and then
i'll create a function called my country
and i'll use
the
global keyword and say a1
and after that
i'm going to
say a1 equal to
i'll change the country to let's say
france
now let me
call the function my country and will
a1
and you can
notice the difference in the result
so here initially i had defined india as
a global variable and after that i am
assigning the
same variable name with a global keyword
and hence it will take
the updated value for e1 and you can see
here the result is france
now finally let's look at
built-in scope in python
this is the final example in the demo
session about scopes and arguments in
python
cool
so
this example is a bit different from the
previous few examples that we saw on
local scope
enclosed scope and global scope
so here
i'm going to
import
pi from the math
module so i will say from math
import
pi
so this example includes
global scope enclosed scope as well as
local scope and of course we have the
built-in scope as well
now what i'll do is
first i'll
give a comment and
create a variable called
pi
equal to
i'll say
global
pi
variable
i'll say this is a global
pi variable
and then
what i'll do is i'll say
df
let's do one thing first of all we'll
remove
the comment
and now i'll create a
outer function
into the colon and say
the variable pi
i'll say
outer
variable
pi
and then
i'll create
a nested function
with the name inner
and
i'll say pi
equal to
inner
pi
variable
now
i am going to say
pi
and
after that i will
call the
inner function
and
next
i'll also call the
outer function
now if i
run this
you can see the result
inner
pi variable being printed which is this
print statement
now
what i'll do is
i'm going to comment out the
global scope variable
and i'll also comment out
the first
outer function variable that i defined
i'll comment this out
and i'll also comment the inner
function
pi variable
now
if i run this
you see the result here
it prints the value of pi that was
imported directly from the math module
or the math library
so here pi is not defined in either
local
enclosed or
global scope so the built-in scope is
looked up that is the pi value imported
from the math module so this is an
example of built-in scope in python that
uses
inbuilt
functions modules and objects that are
available in python
all right
let's glance at the
topics object-oriented programming in
python some major principles of
object-oriented programming and then we
will touch upon topics like class in
python objects
methods
inheritance
the concepts of inheritance the
different type of inheritance then the
definition and examples of polymorphism
encapsulation and abstraction
so all these topics will be
supported with examples
and the relevant terminologies and
definitions
now what is object-oriented programming
python is an object-oriented language
like any other programming language like
java c
and the object oriented programming
language concept is not new
and each and every mature programming
language
has these concepts imbibed in it
now the concept of object oriented
programming in python focuses primarily
on creating project objects and making
reusable codes so whenever we start
programming at a large scale or for a
big project it is very important to
identify the objects within that
particular project which you want to
define
now for example in this
in this
presentation what you are seeing is that
we are covered with full of objects like
car
dog tiger tree or a balloon so these are
typical examples of objects which you
encounter in day-to-day life
now what are the major principles of
object-oriented programming so these are
the different kind of you know
terminologies
classes are there there are objects
there are methods
then on these classes and objects you
apply inheritance polymorphism
encapsulation and abstraction
now what is a class
class is nothing but a collection of
objects or we can say a user defined
data type right so basically it's a
complex data type which has a collection
of objects and within the objects you
have primitive data types like in string
float etc
so a class also holds the methods
the functions
which basically perform operations on
these objects
right and also it also holds on to the
attributes of the objects so let's see
with an example right
so if you have an employee class
then it would contain attributes and
methods such as email id name age salary
these are the attributes and on the
methods like you know perform tasks give
presentation
increase salary
etc etc these are will be the methods
now let's talk about what are objects in
python
now object is known as instantiation of
a class right an object is a group of
interrelated variables and methods
so when a class is defined only the
description for the object is defined
therefore no memory or storage is
allocated at that point
so for example if you see in this
motorbike is a class
but
the different objects of the class are
different kind of bikes by different
brands like bmw suzuki royal enfield so
they all have inherited the attributes
of the class motorbike and then on top
of it defines certain variables
additional variables and methods
on top of it to enhance the motorbike
and make it look different or function
differently now what are methods in
python methods
are functions defined inside the body of
a class right
so basically methods are something which
like
which you which you perform on a
attributes of a class right method is a
function that is that is associated with
an object
so you create an object of a class and
on that object then you can execute
those functions
in python a method is not unique to
class instances
any object type can have methods
and the methods define the behavior of
an object so that's why a bmw motorbike
will be different from royal enfield
because the behavior is different the
methods are different
so if you see the example over here you
have a class bike
and in that there is a init function
which will get invoked when you
initialize the object of class bike and
then you can set the brand name and the
year of manufacturing for that
particular object
now inheritance
what is inheritance inheritance is
something which you derive
from a
parent so inheritance is like creating a
new class that uses all the properties
and behavior
of another class
now the new class is called the derived
class or the child class and the
existing class whose properties are
inherited is known as a base class or
parent class
it provides and the basic view
functionality the usage of inheritance
is that reusability of code
so if anything is defined in the parent
class then you don't need to rewrite
that particular code in the child you
can just inherit it
so as i mentioned let's take a look at
the different types of inheritance which
are available
you have single level in which only one
child is inheriting
the properties and the attributes from
the parent
then you have multi-level in which
first child has inherited from the class
a class b has inherited and then you
have another class c which is inheriting
from class b so this is an example of
multi-level and we will be supporting
all these concepts with an example in
our python
uh notebook
then there is hierarchical then there
are two different classes which are
inheriting from a single class
and then multiple inheritance that
single class is inheriting from two
different parents
so these are different set varieties of
inheritance basis what is the demand
what is the business requirement you can
define
now what is polymorphism polymorphism in
python
what does it means
polymorphism consists of two words poly
and morphs
poly means many and morph means shape
so basically it means
many shapes
so it is it means using a familiar
interface for multiple forms right so
you can use
a single name of the method and which
can perform different behavior
based on the object in which it is
invoked so in simple terms we understand
that a task can be performed in various
ways
let's support it with an example
like you have a plus operator now the
plus operator can be used for integer
data types to perform arithmetic
operations
whereas when you use plus operator to in
string data types it can be used for
concatenation
so it's a very typical example very good
example in terms of
how an uh
same operator
can behave differently bases what data
types are being used
now let's talk about encapsulation
using oops in python we can restrict
access to methods and variable
so basically in
in python you can you can create
something like as private
variables but of course you can't use a
private keyword unlike java so in in
python we use underscore or double
underscore in order to define private
attributes so basically
these attributes can be only used within
the class and cannot be exposed outside
a particular class
so we will see this with an example
now what is abstraction data abstraction
and capsule encapsulation are often used
as synonyms abstraction is used to hide
internal details and show only
functionalities
for example
you know how to turn on or offer light
using a switch but you don't know what
is happening behind socket similarly an
abstract class can not be instantiated
which means you cannot create objects
for this class you can only
define
the methods
which have to be implemented by the
classes which are inheriting the
abstracting
so basically abstract class provide only
the method signatures
and rest the other functionalities and
the implementation has to be done by the
child classes
so let's now move to the
our
jupiter notebook and we will
start performing certain examples
now as we are saying
like python has objects so let's create
object
we will create a class
bikes over here
and within the class
we will define the init method
and
in the init
we will
instantiate two variables brand name and
here
now
we will create an object
of
bike
which we we are calling as bmw and
another we will create an object called
ducati so what we are doing in this
to scenarios is
that we are
just instantiating the byte of bike
object with
variable bmw and ducati we are
instantiating
now
let's
the
year and manufacturing here the brand
name and the ear
for bmw and for ducati and let's see
right so what we have done is we have
created an object for bikes one we are
calling bmw and one we are calling
ducati and how we are differentiating
between these two bytes is basis the
brand name and the year of manufacturing
now
let's take a look at the example of
methods
i'm gonna
rewrite my init method
and now i am
creating an
function
a method
of top speed
and
a function of type
now
i'm gonna
create an object of bike
now this
method this object bike
can invoke methods top speed and type
because they belong to the same class
bytes
so initially when i created my object
bytes i'm instantiating it with bmw and
the ear
and then
i am
making a call to the
method top speed and then i'm making a
call to the method type
and printing
so basically i'm printing the output of
the function top speed and output of the
function bmw
form the object bmw which is of class
bikes
now let's take a look
at an example of single level
inheritance
let's
create a parent class called animal
and
create a
method called sound
and let's create a child class
cat which inherits
animal and let me just put a method over
here
is the indentation
okay
so now i have
object
parent class animal child class cat
which has inherited animal
and the parent class method is sound and
the child class method is meow so now
i'll create an object called cat
and with this object
i'll be able to invoke both child class
method and the parent class method
and as you can see
the child class
has inherited both
parent and child
class functions methods
now let's take a look at
multi-level inheritance example
i'll start off
with creating exactly the same
parent class called animal
then
i am i am already created another class
i'll create
same child class cat
and
now i'll and create another
class which will inherit cat class
so cat has inherited animal and cat
child has inherited cat
let's validate its syntax
and similarly now i'll create an object
for cat child
and this cat child now
can
invoke the same methods
which are in child
parent and the
super parent
so this is an example of multi-level
this is an example of
single level inheritance
now
let's take an example of polymorphism
we are going to click create a class
parrot
and define the function fly
and
now we are gonna create another class
mind you there is no inheritance here we
are just creating an independent class
called penguin
and same methods now the same name
fly
and
swim
okay
now let's make a
function
in which we will pass
an object
and basis
that what is the instance of the
particular object bird it the
corresponding method will get invoked
so let's see
in the method flying test
whatever instance of the bird object
will be the corresponding of method will
be called
so now let's create a
object of parrot class and then
let's create a object of penguin class
now in my flying test
method
first i'll send a object of instance
parrot
and then
i'll
send the object of instance penguin
so now base is the instance type
when this bird dot fly
method will be called it will be
called basis the instance so in the
first case the parrot it will call this
method
and in case of penguin it will call this
method fly
so please note what is the output the
output is a parrot can fly but a penguin
cannot fly
and it has been decided
by the python
at the run time that which particular
method to be invoked bases the instance
so it's a very important concept
now let's take an example of
encapsulation
i'll make a class cars
define its init method
now within that init method i have
created a
private variable with underscore
underscore max price and given a value
of
9 lakh
now i am creating another
function called sell
and in that i am printing the
max price
and then
i am creating another function in which
i am modifying the private variable set
max price
so i will pass any value in the set max
price and it will replace the max price
which i have set during the
initialization at this point
now let's create an object of class cars
and
see if i sell this then the selling
price is
9 lakh what i had in the set at the time
of initialization
now what i'm trying to do is i'm trying
to modify a private variable
directly
c underscore underscore max price
and i i want to check
if i'm trying to create a modify a
private variable
will it still show me 9 lakh or 10 lakh
value and it's still showing me the 9
lakh value it means that i can't
directly
approach or access the
private variable
i can only modify it
if i access it through a
method which is set max price in this
now i am setting the max price to
thousand
and now if i print what is my max price
it will print as
thousand
so this is the concept of encapsulation
you have a private variable which is
accessible within only the methods
of the
class you can't access it directly
now let's take a look at archaeal
inheritance
i'll create a class employee
and
create init method
within that you have
three variables name agent salary so an
employee with has name agent salary
now
i'm going to create a class
child class called child employee 1
which is inherited from employee
and child employee 2
which is also inherited from
employee
so what i'm gonna do is i'm gonna create
a
object
per child class
and
so this is a typical example in which
you have two child
classes which have inherited from the
single parent
ark in narratives
now let's take a look at
our last concept which is abstraction
so now i'll create a class car
and define a method
mileage but i am not
giving any definition to it i'm just
giving a signature mileage
the child
classes which will inhibit abstract
class
will be giving the definition
so i am giving
creating a class bmw
which will again
which has inherited the car abc car but
given the definition now
similarly
i am creating another class
jaguar which has inherited the class car
but now it is giving a different
definition
it's printing mileage 25 kilometer per
hour
and
another class
range rover
and another class
renault
okay
so four classes
which have implemented the abstract
class method mileage in a different way
now i'll create an object of first
bmw
and
invoke method
mileage
so it has method invoke the method
mileage and bmw car and printed mileage
is 30 kilometer similarly
i'll do for renault
jaguar
and
range rover
so if you see
the
parent class
abstract parent class has not
implemented the method but just given
the signature of the method and all
other classes have implemented it and
that's the concept of abstraction
so what's in it for us today
what we will understand what is operator
overloading
and how to overload the operators in
python we will perform these activities
in the jupyter notebook
now what is operator overloading
python operators work for built-in
classes in a predefined operational way
but the same operator behaves
differently for objects of different
classes
so you can make the operator work
differently
bases the requirement you have and the
objects you have defined
so for example the plus operator which
is the most commonly used operator will
perform arithmetic addition on two
numbers or it can merge to less
or if performed on two strings it
concatenates the two strings so it means
the programming language automatically
understands that in which context you
are using the plus operator
this feature in python that allows the
same operator to have different meanings
according to the context according to
the objects which are calling it or
according to the data types which are
being used in that operator it is called
as operator overloading
so if you see in this example 8 and 7
are the operands and the plus sign is
the operator sign
so that is the whole goal of this whole
exercise that we will show you
how you can change
the meaning of the plus operator
depending on the kind of objects or kind
of operands you're using along with it
now how to overload the operators in
python
consider we have two objects b1 and b2
of a class batsman
now we must add these objects with a
binary plus operator
so now the task in hand is that we use
the plus operator to add objects which
is not possible until and unless we
overload this operator
otherwise it will throw an error because
the compiler does not know how to add to
objects it only knows how to add
primitive data types like in strings etc
so basically we will define a method
for an operator that process and that
process is called operator overloading
so in the example which we will be
showing you we will be taking two
objects of batsman 1 and batsman 2 and
we will be using two scores per patchman
and then we will add them so we will
discuss that in the examples we will
show you
now
we can overload all the defined
operators so there's no limitation
addition subtraction multiplication
division
greater than less than so there are
certain magic methods or we can call it
as the primitive methods or special
functions
that are automatically invoked when an
associated
operator is being called
so basically if you have to do the
operator overloading
you basically have to override these
methods in your python program
and that's how you will be able to
override or overload the primitive
implementations
of these functions written in the
compiler of python
so
let's see here in our example right for
example when we use the plus operator
the magic method underscore underscore
add underscore underscore is
automatically invoked
in which the operation for the plus
operator is defined
now we are overloading it and in the
example you can see
we are adding
the
first score of each batchman right so we
have customized the addition function
we are adding the first score of the
first baseman with the first score of
the second batchman and then we are
printing the total so in our case we are
adding
and printing the first one 66 plus 23
and if you print b3 dot s2 you will see
the sum total of 78 plus 59
so the thing to be noted is this
function add function where you are
adding self dot s1 plus second dot s1
and you are adding s self dot s2 plus
second dot s2 and that is the whole
customization what you have done in
order to add two objects of patch
now lets take a look at some of the
examples of operator overloading we have
just discussed
so we will be executing some examples in
our jupiter notebook
now
what i am going to show you
is about
class batsman which we discussed in the
presentation
and i'm going to define the init
function
and
initialize
score 1 and score 2 of the attachment
now
i am going to override
the magic function add
and
add the score 1 and score 2 of the
batsman separately
now with this over
operator overloading
when i will pass
object for addition
then only now my object will understand
that it has to add
score one
of first batsman with the score one of
second batsman
and score two of first batsmen with the
source code two of the second batsman so
we will see how
so what we are doing is
one in the add
operator
we are adding these codes
encapsulating in a new object batchman
and then returning the
object b3 now let's create
object b1
batchman1 and batchman2
now i am
adding two objects batsman one and
batchman two
now without operator overloading if
would i would not have done operator
overloading of add then this would have
failed because plus operator does not
understand the object's batsman but with
overloading done
now i can independently print the score
of
the new batsman the batsman's the b3
object
some of score one of batsman one and
uh score one of batsman two which is 66
plus 23.
okay
so now let's take an example of a simple
operator function
like for example i'm gonna
simply create a variable a with value 44
and variable b with 7
and
print a plus b and if i run this
this is the expected output
python plus operator knows that a and b
are
primitive int variables so it's able to
add that
now behind the scenes when we printed a
plus b
actually this is what happened
in
primitive in variables add operator
overloaded method got called
and a and b got passed and 51 was
calculated
so it's automatically done because this
function is implicitly written in the
python language
similarly
i can also do this thing i can create a
int variable
and a float variable
and if i try to print it
i will get the expected output which is
50.5 because the plus operator accepts
the end and a float variable it's
implicitly written so that is also
allowed
now let's take another example of
string operators
string variables
addition
now irrespective of my
i'm giving numerical values in the
string print a plus b
in string
is is meant to do concatenation
so
446.5 it's a simple string concatenation
what python has
Can't find what you're looking for?
Get subtitles in any language from opensubtitles.com, and translate them here.