Transcripts
1. Welcome: Hey, there. I hope your
day is going fantastic, and together, let's
make it more enjoyable. I'm not going to ask you formality questions like,
how are you and all. I already know
you're doing great. After all, you have dared to
learn something new today, and that takes a
good mood, right? Otherwise, you would
have been binge watching cat videos or scrolling
through memes right now. Anyway, welcome to
the Python world. You need not to fear in this world because
here the snake or the language that has
got its name from the snake is very friendly. You have just tapped into the world where
coding is easy, fun, and feels less like learning a new language and more
like solving a fun puzzle. First off, give yourself a pat on your back
because simple, I cannot do so for you. Okay, do so for deciding
to learn Python. Python is very sweet, and this journey is
going to take you from I have never
coded in my life. I know Python coding very well. This course will lay down a solid foundation of
knowledge in Python. You may ask, What shall I
do with that foundation? Whatever you want,
that is up to you. Python is common foundation
for various domains. You can use it for multiple
purpose, web development, data analysis, machine learning, automating tasks, building
games, you name it. Python has got it covered. And the best part, it is
easy and beginner friendly. You won't need a computer
science degree or a brain the size of the
moon to get started. It is easy to read, easy to write, and it
forgives your mistakes. It is like the chillst
teacher you have ever had. No matter what your
career goal is, Python welcomes you
with open parenthesis. If you have the thirst
for the knowledge, this course will guide you
to the lake of Python. Remember, we can
only lead you there. We can't make you to drink. It is up to you to
consume this knowledge. But how? Just follow
three step process, practice, experiment, and
apply, and that's it. Promise me you follow
these three process. Not just for programming, you can follow these steps
to learn almost any skills. But if I have to
make that statement, I have to give a quick
disclaimer for my safety. Don't experiment if
you are a doctor or a pilot unless you like
living on the edge. Do so at your own risk. I'm not responsible
for any consequences. I hope it is clear. Let us come back to the
world of Python. By the end of this course, you will not only
speaking Python fluently, you will also be writing it. The best part is you will
enjoy the learning process. Are you excited? Give me a
virtual hi fi, but be careful. Please don't knock your
computer while doing it. You're still half asleep, raise your virtual coffee mug, but no promises it
will wake you up. Are you ready to
start your Python adventure, gather some snacks? Let us dive in together, have some fun and write some de, trust me, it's going
to be awesome.
2. Introduction to Python: Welcome back. In this session, we are going to cover everything you need to know about Python. It is important to know about our new friend before
we go forward together. Python has become so popular
in the recent years. What is Python? Why
it is so popular? It is the time to
answer this question. Python is open source, high level general purpose
programming language. I know a lot of new words
that doesn't make it cool. As I promised, let us break it into small
consumable bites. Let us understand
what is open source. Have you ever planned
potluck party with your friends where instead of one person
cooking everything, everyone brings a dish. Now, here is the
cool part about it. Not just you all get to eat the variety of delicious food, but everyone also
shares their recipes. Want to add some extra
spice to the curry. Go ahead. Think the cake could use more
frosting. Why not? You can tweak, change, and improve every
dish as you like. That is exactly how Python or
any open source tool works. It is like software that
is a potluck of code. The recipe or the source
code is publicly available. Shared with everyone,
and you can modify it, improve it, or even mix it
with your own secret sauce. The best part, you can
eat or use it for free. And being community driven, anyone can take
the responsibility to make it a better one. That is how Python is getting
better and feature rich. So first term, open
source is digested. The term general purpose
programming language is very straightforward. It means the language is not specialized for any
specific domains, but is designed to
solve variety of problems and can be used for
wide range of applications. As we discussed
in the beginning, Python could be
used for variety of applications ranging from
software development to analyzing the data. Python is among the general
purpose programming language. Then what do the term
high level language mean? Is it talking about the social
status of the language? No. But to understand that, we must know the different level of programming languages. The early generation
computers used to understand only the binary language just
composed of zeros and ones. That is the native language that computers speak fluently
and understand better. This language is also
called as machine language. Even the programmer is supposed to communicate
with the computers through this alien
machine language full of zeros and ones. It is super efficient for computer to understand
and process. But what about us?
Let us be real. If we had to talk to computers
in just zeros and ones, we would all be crying
within 5 minutes. Unless you enjoy typing
out long strings of zeros and ones just
to say hello world. It is not practical
for us humans. Imagine, we need to
program the softwares and complex calculations using
that strange language. Just imagination would
make me feel horrible. Then how about it in actions? To resolve that,
programming languages are developed that can be easily
programmed by the humans. All modern applications are developed using the
programming languages. These languages can
be classified into low level languages and
high level languages. Popular low level languages
are CC plus plus and Fortran. C plus plus is arguable
because it can be both low and high level and hence it is called
mid level language. These low level languages are closer to what
computer understands, but they give you a
bit more control. Think of them as the manual
transmission of programming. You get more control over
the car, I mean, computer, but you have got to do all
the hard work yourself, like managing memory
and processes. Low level languages are great when you need
speed and control. But let us be honest. They're not always the most
fun or beginner friendly. Then we have the
high level languages like our buddy Python. These are designed
to be more like us, human readable, easy to
learn, and very forgiving. High level languages are
like using smartphone app, simple interface, and no need to worry about what is
happening under the hood. Even among the members
of high level languages, Python is one of the easiest and beginner
friendly language. If you can understand
plain English, you can understand Python. Python is known for its
simple English like syntax. If you understand me right now, you are already halfway there. Python is so easy that even
your pet could understand it if your pet had advanced cognitive
abilities, of course. Don't blame me later if your pet doesn't become
the next coding prodigy. And also how many times have
you heard Life is short? Yes, it is the hard
truth of the life. Then why waste
precious time writing long convoluted code when Python can do it in fewer lines. Python simplicity
saves your time, effort, and possibly a
few stands of your hair. Most Python programs are written with at least 30% fewer lines of code compared to other popular languages
like C plus plus and Java. But that doesn't mean
the computers of present day has forgot its
native binary language. Even the modern computers
use the machine language. But it is restricted to process the information and to communicate with each
other fellow machines. That is obvious. We all have some native language or some
call it as mother tongue, the language that our parents
used to speak at home. When we think when
we speak at home, we use our native language because every cell of our
body understand language. When we grow, we learn other
languages as per our need. But our brain first translates the new language into native
language to understand. That is very common. That is exactly how
computer works. When computer thinks or process the data and talk
with other computer, it always use binary language. When we program using any
programming language, computer translate it into machine language and
then process it. Hence, high level
languages consume more time to process than
low level languages, and machine language
take least time to process as it is the native
language of computers. I hope the machine language,
low level language, and high level language is processed properly
in your brain. Apart from being easy, beginner friendly and
least number of lines, there are many other
reasons to love Python. Well, Python is like the Swiss Army knife of
programming languages. Super versatile, easy to use, and it can handle just about
anything you throw at it. Here are a few reasons why choosing Python
is a genius move. The first reason, Python is versatile and it
is cross platform. Python is like water. It fits into any container. It works across all
major operating systems, whether you're
coding on Windows, Mac, or even Linux. Python works on all
of them like a charm. It is like that one friend who gets along with
everyone at a party, and you can use it
for the projects in various domains without
breaking a sweat. Second reason, Python has a library of libraries,
thousands of them. For any domain you
are interested in, there are likely a library
or several to help you out. Data science, web development, artificial intelligence,
you name it. Python has a bunch of
libraries to solve them. If you don't know
about the libraries, it is pre coded resources help you to solve the
complex problems. Think of Python libraries like the bunch of
pre coded tools. You can just grab off the shelf. The real challenge about
the Python library is choosing the right one from all the options
available for you. Do you need another
reason to love Python? Python has massive community. You get friends,
not for parting, but they share common interest, who would help you in
programming journey. Need help stuck
with the problem, and trust me, it will
happen while programming. Chances are, someone else has
faced the same problem too. They might have got some error
as you do, and guess what? They have already solved it
and posted the answer online. Just type your problem
or error into Google, and there is a good chance someone has already
explained how to tackle the problem or error in some platform
like stack Oflow. You are never alone in
your Python journey. And what if you want
friends for a party? Well, that's another story. But you can count me
in always anytime. With so many reasons in favor, Python is really attempting
language to learn. But before you start
thinking, Python is perfect. Let me be real with you. Like all the good things, it has few setbacks. First up, Python is little slow, not slow like a turtois, but compared to faster
languages like C plus plus, Python takes its time. But for most of the programs, this delay is not
even noticeable. When you are coding
heavy video games and heavy processing
back ends of a software, you may realize
Python is bit slower, but you have saved a lot
of time while programming. There are few areas where
Python is not the good fit. The first thing is mobile
application development. If you are dreaming of building
the next big mobile app, Python might not be a GT. It is fantastic
for backend stuff, but for mobile, it
is not the best. Another area where Python is not a good option is front
end development. If you're wondering what this
front end development is, front end is the interface of any software that is
visible for the user. Back end is all those
things like calculations, interacting with the servers
that is happening behind the scene under the hood and not at all
visible to the user. Python is good at
back end development, but not for the front
end development. But hey, these small
issues are like finding a tiny scratch
on the shining surface. Let us celebrate
Python for what it is, not what it is not. And that is why
Python is used by many top companies
and organizations. Ever wonder how Netflix know
what you want to watch next? Yes, they are using Python. To sum it up, Python is like the superhero of
programming languages, flexible, powerful,
and easy to learn. Whether you want to
automate boring task, build websites, or dive
into data science, Python has got you covered, and that I hope makes you know everything that you are
supposed to know about Python. After the good introduction, we can start our
journey officially with Python. See you soon.
3. Programming Interface: Now I will give you a
simple and easy task. Look at these hairless
and earless people and recognize their profession. It is a very easy task, right? You hardly need
seconds to answer it. Okay. Done. I have a few
questions for you now. Do you know these people before? Are they your neighbors or
do you meet them regularly? Don't think so because even I don't know
or met them before. Then how did you
get to know about their profession when you
don't even know them? Obviously, the tools they use tell about their profession. For any profession, the first requirement is having proper set
of tools to work. That means even
programmers need tools. First, they need computers
and necessary hardwares, but very important tool in the programming is installing the platform for
writing the code. Think you have understood
already to learn and use Python or say any
programming language, it is important to install the platform to write
and execute the code. For Python, you have a lot
of options to choose from. Actually, that is
the real problem. With the more option
and freedom comes the more confusion.
Which one to choose? You can use editor or developing environments
like VS code, Pycharm or Spider for
Python programming. Can even use Jupiter Notebook, which is open source web based application
runs on browser. All these platform
offer free version. How sweet. This is the best word one could
hear in this world. You can use multiple platforms if your hardware
allows you to do so. If you're using Python for data science projects or
for scientific computing, it is highly recommended
to use anaconda. Don't go to Amazon searching it. I don't mean that big snake, but popular Python
and R distribution. Anaconda has important
packages pre installed in it, and installing any new
packages is also a bit easy. You can use the
different environments and choose whichever is
comfortable for you. Now I'm taking
Spider, for example. Don't worry, I'm not
talking about the insect. I don't know why Python is so wild that it is
mostly associated with the names of animals,
Python, Anaconda, Spider. I don't think these animals
use Python regularly. If you know, then
please let me know. Okay. Look at the interface. Here is how it looks. Part where we write
the program is editor. You can interact and get the output printed in
the part called console. I will write simple
lines of code. Don't get afraid
about the program. It is just for demonstration. I'm just printing the
version of Python I'm using. Save the script
you write locally. Now it is the time to
execute the program. To run the program, click on the run menu or alternatively, click on this sleeping
triangle shortcut. You will see the
output in the console. Almost all editors have
similar interface. In this training session, we use Jupiter notebook as interacting is
easy and dynamic. The interface of Jupiter
notebook will look like this. In the Jupiter notebook, rectangle you see here is the part where we
write the program, which is called code cell. To run the program in code cell, click on this square. Shortcut to run the program
is Shift plus Enter. The result you are getting is the output of this
particular cell. You can write the next code
snippet in the next cell. Jupiter notebook has
that simple interface. To better understand and get
the hang of the interface, you need to go to the interface and try to work on yourself. You will understand better. I think this introduction about the interface will be
enough to get started. Other things you are supposed to know about the interface, you will explore on your
own when you practice. Now comes the interesting part. From the next video, let us
start writing the programs, see you in the next class.
4. print() function: With all that good introduction, it is good time to start
writing the simple programs. You tell me now, which is the simplest program
one can start with. Before going through that, first answer this question. What is the basic task young
kid or even parrot can do? The simplest task that a kid or a parrot can do is
repeat what others say. That is the easiest thing
one can do in this world. That answers our
original question too. Most basic task Python
could do is print the input statement as it is like parrot
repeating the words. To make it clear, printing
the message like hello world is the most favorite program of every beginner in any language. It is the time to introduce
the first friend of coding, the parrot of Python,
the print statement. Syntax is write print, open parenthesis and include your message or statement
within single or double code. That's it. Now let's
run the program. Congratulations. You
wrote the first program. Try yourself with any
message like hello world, but strictly use single
or double codes. Otherwise, you get error. Python won't bother what you have written inside
the print statement. It prints whatever you ask for. Now you know Python print
the text within codes, but there is a problem. Sometimes we may need to include single or double codes
within the statement, like highlighting a
word or apostrophe, like in this example, but using the code within the input statement will
confuse the Python. Such usage make it difficult for Python to understand
which is the start and end of the input
statement inside print and totally
disturbed input statement. Python says, Hey, man, I don't understand
what you want to do in its own language
by giving error. If you're supposed to
handle such situation, we must explain to Python in
the language it understands. Here comes our new friend
backslash for help. Whenever codes need to
be used within the text, use backslash before the code. This tells the Python
that we need to include the code for
the printing statement. Python understands what
it is supposed to do. You get the required output
without any problem. Backslash help you to
solve one problem. Before you thanking backslash, you need to know more
about backslash. Backslash help us in multiple
ways while programming. To be more precise, backslash is used to give
special message for the Python. Let us explore a few of them. One such usage, backslash
N gives the message to the Python to end the current
line and start a new line. So do you love to use
Imoges in your program? You got covered by backslash. You can print the faces
also using the backslash, but you need to remember the unique codes of
each of the faces. We don't use Imoges usually, so we don't dive deep into it. I hope you have understood
how to use print statement. Print is one of the predefined
functions in Python. There are many such predefined
functions like print in Python that you will see
throughout this learning. Print has easy syntax, but some function may
not be as easy as print. When you have doubt on
how to use any function, you can get help from
Python directly. After learning
only one function, you are too early to get
doubt on how to use it. I know you are very capacitive, but in case while working with the Python predefined functions, if you're struck
with the question, how to use the function, get the help directly
from Python. Who will know about Python
better than Python itself. For that, just type help and include the function
within the parenthesis. Pan gives the information about the function like what it
does and how to use it. Help will help you on your way and one more
thing to remember. Be ready to be comfortable
with the errors. You will regularly face a lot of errors
while programming. Most of the time, errors are self explanatory
like this error, zero division error,
division by zero. If you know mathematics, then you understand that integer cannot be
divisible by zero. In case, if you get error in the program that you
do not understand, simply ask your most knowledge teacher
ever in the history, the Google by searching
the error name, you likely get the answer. As discussed earlier, the big Python community help us in resolving the error
in different forums. Python is cool, Printing any message will take just
one line of code in Python. The simple syntax
of Python reduces a lot of effort that are
required for other languages. We have just kept
one step ahead. We shall explore more
interesting syntax in upcoming videos.
5. Python Datatypes: Welcome to new model
on data types. Before understanding
the concepts, let me ask you a
simple question. Can you build any product
without using raw material? Silly looking question
as answer is obvious. Building physical product
is not at all possible. But someone might be
thinking smartly that it is possible in case of digital products that are
built using software, then you are wrong again. Even the softwares or programs
need the raw material, but this raw material
will be different. Physical product need
physical raw material, but for programs, material is not
in physical form, but is in the form of input data and instruction of
what to do with that data. Data and instructions are the
raw material of a program. So for any program, data is a necessary part. In this module, we shall understand about the
data in more details. We first get to know about our neighbors before
making them friends. Similarly, getting to
know about data is very important step before
start using the data. Just like there are
many categories of people we see in this world. There are many types of data and we need to
handle them differently. For example, companies collect the feedback from the customers
in the form of text data. They process and publish financial details in the
form of numeric data. Some data might be in
the form of images, some in the form of
video like this course. We gossip in the form of audio and there are
many other data types. Just like we deal differently with different types of people, it is important to know the type of the data before
we work with them. It is the time to explore the types of data commonly used. Python data has six
popular children. All children are different
from each other. They are numeric sequence, mapping, set,
Boolean, and binary. Now make some time.
We shall attend the data types party and shall
meet each of its children, know them better and know
about their children too.
6. Categories of Python Data: Welcome to Data types party. We are here now to meet each of the family members of
data types one by one. We shall first meet
the sequence type. The term sequence in English indicates the series of
related things or events. You might have heard
of sequel of a movie. The term, you might have understood sequence
data never come alone because each member of sequence has their own gangs. That means sequence does
not refer to single value, but to the collection
or group of values. Sequence has three kids, string, list, and tuple. In this module, we meet only string because list and
tuple are not just data, but the collection of data belonging to same or
different data types. Hence, we will have a
detailed meeting with them in the model
Python data structures. Okay, let us start
understanding string. String is best storyteller
of Python or any language. I said that all members of sequence type have
their own gangs. String has gang of characters. These set of characters
form the word or sentence. In the simple term, it
represents the text data. Text data is something
you know in and out. All written contents in email that you have
sent to your boss, SMS sent to your girlfriend, comments and feedback
collected from the customers are among
the examples of string. The text data you see
here is a string. Earlier we saw the print
with input statement. I hope you have not forgot it. That statement inside
the print function is also a string. String is king of data
types and hence require a special treatment to be included within single
or double quote. That makes clear why
we need to include the input statement inside
codes for print statement. Because the statement we
have provided is a string. When we use other data
types in print statement, we do not use codes. We shall see later how print statement handle
numeric and other data. Fine, I have got a
piece of data here. How can I confirm the type
of the data I'm using? Is there any function
to know the data type? If you want to know what
is the type of the data, just type type, confused. Yes, it might be,
because we have used a sequence of
types in our sentence. I will make it simple. I mean, use type function
with the data within. Type is asking the piece of
data to introduce itself. It replies that I'm
string in this case. We shall learn about string
with much more details later. This is just introduction
class and we shall meet the other two
gangsters list and tuples later. As they are gangsters, you cannot meet them easily. Just kidding, even
they are very sweet. Both list and tuples
are collection of data belong to same or
different data types. We shall understand
other data types and their applications first, and then we can proceed. Moreover, both of them
have gang of elements. Only difference you
may spot is list is included in brackets and
tuple has parenthesis, but there is much more
difference among them. Hence they feel similar
and may confuse you. We learn about
them detail later. The next child of
Python data, numeric. Its name speaks a lot. It is not the cool data type for those who are
allergic to mathematics. Numeric family is a math love because they all are
good at mathematics. It has, again, three children, integer, float and
complex number. Want to meet these
kids? Why not? We came here to meet the
whole family of data types, so we shall meet these kids too. Eat first child integer. Integer represents
literally any real number without the tile
of decimal part. It never deals with fractions. Integer can be a whole number, including zero and
negative number. All value you see in the
cell are integer data. Integer is okay with anything, say positive number,
negative number, or even zero, but it
hits the decimal part. If there is decimal
part to the number, then integer will become angry, kicks them off from
their territory and abandon data gets into the
next category that is float. Float is short name of
floating point numbers. Floats are real numbers
with decimal part. Adding just 0.0 to an integer will not change
the value of the number, but change the data type
from integer to float. The programs involving heavy
numerical calculations usually get flooded with
floating numbers than integers, and it is more practical. Look at this simple example. Dividing an integer with another integer can make the
resulting value a float. Hence, I told float
is more practical. Apple with orange cover over it doesn't make the
apple an orange, but numerical data within single or double coat
represents string data. Never use coat with
a numerical data. Not just numerical data. Do not use it with any
data other than string. Another numeric data
type is complex number, which is complex as
its name suggests. It has complex part
root minus one. In mathematics, complex
number is represented by I, but we are bit different. In Python, complex part
is represented by J. This change is because Python love electrical engineering
more than others, and in electrical, I represents current and J represents
complex number. Remember this while using
the complex number. The next family we meet is map. The mapping is the
type of the data where the information is stored in the form of key and value pair. Key is the clue for the data
stored in the form of value. If you could crack the key like Sherlock home
finding the clue, then finding the value is KK. Now come to the next
datatype that is set. Like list, set also roam
around with its team, but each member of
the set is unique. That means there is zero
tolerance for duplicate entries. The team hides
inside curly braces. There is also logical datatype
in Python that is Boolean. Booleans are like young kids
who always tell the truth, but do not give any other
information than true or false. They can speak only
these two words. Even though it talks less, it is very important
data type to check conditions that we
see in details later. Boolean values are
case sensitive with the first letter in upper
case and rest in lower case. Otherwise, Python do not
treat it as boolean. Don't put the boolean
values in codes. Otherwise, they will be
considered as string. And finally, binary is the secret agent of
Python data types. It uses the secret
language to communicate, which is in the form
of zero and one. This is the language with which computers talk
with each other, store all the values
in its memory. Use zero B in the beginning to tell the Python that
this value is a binary. Otherwise, Python will think
the value is an integer, as it is the language of computers that we
do not understand. We do not talk much about it. I hope you have enjoyed the
party of Data Types family. All members of family are unique and has their
own significance. I know you could not
communicate in detail with some of them,
but don't worry. By the end of this course, you get the chance
to talk with them. See you in the next class.
7. Datatype Conversion: And I assume you have many friends and relatives. You have got friends from
school, university, work, and might be some
from social media and friend like me
from this course. But how many of your friends
are your best friends? Hard truth of the life. I'm sure very few of them. Is there any reason we like
some people more over others? There could be many
reasons, but very commonly, we love to connect with people having something
common among us, like same school, profession, similar likings, to name few. But why we are discussing
psychology in Python class, there is a reason even
data belonging to same data types
like each other and they can be operated with
each other effortlessly, like adding two integers,
float or string. But data belonging to different data type can also
be operated with each other. For example, we
have two numbers. One is integer and one is float. Both belong to
numerical category. You can add them and the resultant number
has a decimal part. Hence, it is a
floating point number. Here, Python first
converts integer into a float and then add
it to another float. Python do it by itself without asking your
permission to do it. This type of conversion
done by the Python without the help of the programmers are called implicit conversion. But there are some cases
that arise while programming where we need to convert the data types manually
using functions. Here are a few examples to
understand how it is done. In first case, input data is a numerical data
enclosed within codes. By default, Python
treated as a string, but it is an integer
from its heart, we shall bring it
to its actual type. We manually convert the data
into integer using function. In this case, again, the data is numeric, but according to Python,
it is string. Using the float function, string is converted into float. Next example, data
is an integer. We use STR function to convert
the integer into string. And the last example,
data is float. Using the int function, we cut the decimal part of the float and convert the
float into an integer. These are the few examples of
converting the data types. These int, float and STR function doesn't care about the datatype
of the given data, but try to convert
them into integer, floating point and string data type
respectively, if possible. You can try a few other examples like integer get
converted to float. This type of manual
conversion of data type where you,
the programmer, request or order the
Python to change the datatype is called
explicit Conversion. I know you ask about the
application of these concepts. Let us go step by step. We shall see their application when we proceed with
the programming. As of now, I'm feeling hungry. I will convert the batter into bread using explicit conversion.
8. Introduction to Operators: In this module, we shall go back to our initial school days. We all started learning
mathematics in school with numbers or anyone else here who started with
calculus or trigonometry. I hope everyone started
with numbers and counting. But knowing just
numbers is of no use as solving any numerical
problems need the operators. Actual learning of
mathematics has started with the operators like
addition and subtraction. Computing without operators
is same as lock without key. It is just useless. Hence, operators are the key requirements
of problem solving. Same or similar operators, we use in Python for
problem solving. There are three categories of operators we use in programming, arithmetic operators, comparison operators,
and logical operators. Remember, operators are
the spices of programming. They just give more flavor
and fun to the boring codes. No concepts we learn in
this module is new for you. Most of the concepts are same you have learned
in your schools. Hence, this module will bring
back your school memories. Are you ready to time travel
back into your childhood? Let us go back to
our primary school to brush up the concepts
of operators one by one.
9. Arithmatic Operators: What is the key requirement
of any numerical calculation? Don't tell me you
need a calculator. I know you're very smart. Even calculator cannot calculate without the
arithmetic operators. Let us start with the basic
arithmetic calculations that we have done in schools, like addition, subtraction,
multiplication, and division. What else can be easier
than this? Let's start. Addition is an adhesive which bring the best friends
together forever. You know, you can
add numeric data. I assume your teacher
taught addition well so I don't go deep. But one thing, first two
lines have numeric values. First line has two integers and second has two floats,
which are added. Never use code for numeric or any value other than string. Addition of these values are performed and results are
printed in the order. Can observe here, we can
even add two strings. Adding two strings will
concatenate them end to end. That means second string is joined at the end
of first string. That's all about addition. Subtraction is a magical stick, pulling out the two
slices of pizza from four and make it disappear,
leaving behind 02. I don't want to be your
early school math teacher. You know it already,
and let's move on. Multiplication is a
photocopy machine that produce duplicate copies. It is taking five documents
and making six copies each, producing 30 copies total. Division is nice
and honest friend who divide the treat equally. In programming, asterisk is used for multiplication and
slash for division. Multiplying a string with
an integer result in repeating the characters of the string that number of times. But you cannot use division
and subtraction on strings. These operators are simple, want to learn new operators. There is a special division
called flow division, which use double slash to return on the integer
part of the output. This is useful in situations like dividing the
people among teams. For example, in this case, seven people need to be
distributed among four teams and how many people each team can accommodate if strength of
all teams must be the same. If you use division,
it says 1.75. How can we cut the person? Number of people in each team cannot be decimal
if they're alive. Floor division return the
integer value after division. Each team can accommodate only one person what to do
with the rest three people? Let us come back to it soon. Another popular operator
is exponential. Exponential make the
things super big. Double asterisk does this task. Here, two is rises to the power
of three, which is eight. This magical operator
make the two into eight. The same operator could be used for the roots, for example. Power of one by two represents the square root and power of one by three for cube
roots and so on. Nine raise it to the power of half is square root of
nine, which is three. 64 rise it one by three
is cube root of 64. The value has a lot of decimal, still this value is four,
as you can observe. We shall see rounding
the values later. Look at one more operation, modulo, which use percent sign. Don't think it returns the
percentage of two numbers. It returns the reminder when first number is
divided by second. Want to understand more.
It is very simple. To understand this,
recall floor division. In floor division, we distribute the people equally
among the team, and leftover people make
their own team of reminder. We have seven people to
divide among four teams. We have provided one each
leaving behind three people. These three make their own team which is strongest
than the other teams. If we can divide
all people among the teams, like in this case, where nine people need to be
divided into three teams, which can equally accommodate
three each person, then obviously the
remainder is zero. After distributing equally,
no person is left out. You got to know the
arithmetic operators. When we use operators
in combination, use parenthesis for
prioritizing the operators. You can look at the order
of priority in this table. Python follows this
order for operations. The calculation within
the parenthesis is carried with priority. Operations in the
innermost parenthesis, which has highest security from the parenthesis
is carried first. Two plus three and three plus
four is processed first. Then both value after addition, five and seven are individually rises
to the power of two. This is because exponential has more priority than addition. Five squared is 25 and
seven squared is 49. Then finally, both
are added to get 74. This is what we have
done in cube root of 64. 1/3 operation is protected
within the parenthesis. Hence, it is carried out first, then the resulting value
is used for exponential. You have the control of priority just by using the parenthesis. If you need more time to
watch and read the table, then I will give permission
to pause the video. I am sure arithmetic
operators are super easy and
comparison operator, which we see in next module is also very easy concept.
We shall meet there.
10. Comparison Operators: Do you know what is the one
big bad habit of humans? I know we are loaded
with bad habits, but your task is to find one bad habit that kept us
away from the happiness. Guess, we humans always
love to compare. If you are not guessed
it correct, don't worry. It will not be
asked in any exams. Always judged by
comparing with others, maybe in terms of beauty, education, career,
salary, and whatnot. Comparison might be
the major reason for unhappiness for us. But in programming, comparison is an important parameter
in making decisions. For example, if
you're working in company A and you are
offered job by company B, how will you make the decision Silly by making the comparison
of different parameters? First thing we look at is
salary, who don't like money? If salary offered by company B is higher than
your current salary, then switch, otherwise, stay
back and try your luck. I can hear someone
saying you don't make the decision just
based on the salary. I need to compare many other parameters like project role, work environment,
work life balance, what your neighbors think about both companies and many more. Again, all these parameters
need comparison. In mathematical term, we use comparison operator
for this purpose. Which are those operators
we use for comparing? I'm sure you know these two. Here are the list of
comparison operators used in Python and result of these operators are Boolean data type that
is either true or false. If the provided
condition is satisfied, it return true, and if the condition is not
satisfied, it returns false. Let us understand
them one by one. Greater than is the
judge of talent show, which always look for
the highest scorer. If the value on
the left hand side is greater than the value
on the right hand side, greater than return true, if not false, here seven, which is on the left hand
side, is greater than five. Hence it return true. If the values are equal,
like in this case, where both left hand side and
right hand side has five, the outcome will be false. Because as its name suggests, it strictly look
for greater than. For the special purpose, we have greater
than or equal to. Greater than or equal to is the fellow judge for
greater than who is a bit liberal and consider the one who has similar score
two and pass them. It return true when the value
on the left hand side is greater than or even equal to the value on
the right hand side, so it is a bit liberal
than greater than. If you understand this well, then we will have
just opposite of it. Lesser than and lesser than
or equal to are the judges of race computation who check for the least time to
achieve the target. You tell me now the outcome of this condition is five less
than or equal to three. Five is neither less than
three nor equal to three. So you get false. The next operator is equal to. Equal to look for perfect match like matrimony site which look
for the interest matching. If both values are same, it return true,
otherwise, false. Use double equal
symbol for checking equality as single use indicate assigning the
value to variables. Another scary looking
term, variable. We have a separate
module on that. Coming back, this time,
let us use string. String ABC is checked with ABC. They are equal, so true
is 5.0 001 equal to 5.0. Comparison operator
are very strict. Even if the values are very
near, it return files. There is an opposite to equal to that is obviously not equal. Adding exclamatory sine before equals indicate if the
condition is not equal to. This is a weird operator who do not like the identical twins. This operator returns false when both values on left hand side and right hand side are same. In any other case,
it returns true. Phi is not equal to three, hence it is true. Hope none of these
operators are new for you, but the operators
used might be new, but still they are easy. Here we see a few of the
tests of comparison. If you have understood the
concept of comparison, this test doesn't
need any explanation. Still, I will make some time
for you to take around. In the first case,
programmer asked the Python, Hey Python is three
less than two, three is definitely
not less than two. Do you expect the output to be? Whatever your
expectation might be, but Python says no, by returning the output false. The next case is three less
than or equal to three. Three is definitely not less than three to best
of my knowledge, but it is equal to three. Hence output is true. If there was less than operator here instead of less
than or equal to, then story would be different. Nothing serious will happen, but you would have got false. That's it. Is three
greater than two. Yes, it is two greater
than or equal to three. If three is not less than two, then how would two is
greater than three? This game is not so interesting as you know the result of these. So I will stop here. You can look at other
operations. Easy, right? And don't think two and
three are my lucky numbers. I'm just a bit lazy to
find other numbers. Before we end the lesson, can we compare two
values belonging to different data types?
At this example. In the first line, a float is
compared with the integer. It is totally fine
to compare them because they both belong
to numerical data types, but it is not okay to
compare the values with strangers like string
in second line. Comparison is okay,
but in programming, there are few use cases where we need to combine two
or more conditions. It helps us to compare multiple condition before
we arrive at the decision. We connect two or
more conditions using logical operators which
we see in the next class.
11. Logical Operators: This word is very peculiar. We cannot make decisions just by considering
one condition. We need multiple conditions in the favor for higher
probability of success. Forget that difficult
philosophical sentence. In simple words, what I
mean to say is we cannot make decision just based on
comparison of one parameter. In the previous
lesson, we have tested multiple comparison
conditions individually. Some case, we use multiple comparative
statement before coming to a decision and these
conditions are combined by a class of operators called
logical operators. Even logical operator is something you know already
and use them regularly. There are three logical
operators commonly used. They are and and
not familiar words. We use them regularly
in English. Their logic as a
logical operator is also similar to
that of English. Let us see them as logical
operator one by one. First, let us start with and. Imagine you go to restaurant, you order pizza and sauce. We use and in between pizza and sauce because there should not be option of having any one. You strictly need
both to be delicious. How can I just eat sauce without pizza or
other way around? Can I say it in
programming term as both conditions need to be true for getting the
conclusion to be true? This is an example of
two conditions and there could be use cases of more conditions
to be satisfied. Logic behind and is all conditions need
to be true for the conclusion of the
statement to be true. And is a strict professor who does not like to compromise
in any situation. It expects every condition to be perfect true for the
conclusion to be true. In other words, result of and is true only when all
conditions are true. Otherwise, it's false. For example, is six greater
than five. Yes, it is true. I six less than ten unless
you are a preschool kid, you know very well that both
these conditions are true. So both conditions are true and hence resulting and
condition is true. Take the example of
multiple conditions. Here, all conditions are true. Hence the result is true. Nine conditions true with
just one condition false, make the whole statement false. I hope now you perfectly
understood and condition. Now let us move
to next operator, how you use R in your routine. When you go out
with your friends, you like to have pizza or
burger, whichever is available. What this R is saying, you need any one of them
to get your stomach full. If luck is in your favor, you get both, which will
make you fully satisfied. I interpret this
as even any one of multiple conditions in R is satisfied or found to be true, the whole statement
will be true, right? Our statement is
very optimistic. Or statement will be false only when all conditions in
the statement are false. Otherwise, it will return true. Unlike condition, even if one among ten
conditions are true, then output is true. There is one more
logical operator, not get back to the old story of restaurant
with your friends. Imagine restaurant
has only two options to eat pizza and burger, but you do not like pizza, so your order condition
is not pizza. By using the logic knot, you mean you are okay with
anything except pizza. So you are left with no other
option than eating burger. Same logic do not operator
carry in programming. In conditionals, you have
two options, true and false. If not true, then
it must be false. In some way, it is
like your spouse. If you are true, it is false. If you say false, it
will become true. Is one greater than ten. No, it is false. Not operator which heads whatever comparison operators
say and does the opposite, say this condition is true. I hope you have digested
naught operator to. Comparison statement
and logical operators are very useful in conditional if statement and in loops like four and Y loop. We shall discuss about
them in later part. Here is one simple example
of using logical operator, but why English alphabet
appeared suddenly. But this code is still
easy to understand. A is the name given to the value six and then we use its
name instead of value. A modulo two, that is six modulo two is zero as six
is divisible by two. Six is less than ten, also six is greater than zero. All three conditions are
satisfied in this statement, so result is true. Similarly is this example. Here, value is the name
given to the value 13. The value 13 satisfy only
one among three conditions. That is value is
greater than zero. Only that condition is true. Both others are telling lie. But these conditions
are joined by operator, which has kind big heart enough to excuse two
falls among three. R operator will be
happy even when only one among multiple
comparisons are true. That is the optimistic
nature of operator. Hence, I told operator
has kind big heart. In these two examples, values are given
with distinct names. This naming ceremony is
called assigning variable. This is the ingredient
of next module. I'm inviting you to
the naming ceremony which occur in the next module.
12. Variables & Identifiers: And Welcome to the land of variables and identifiers. Think about it. Just as each
of us has a unique name, so do the piece of data we
work with in the programming. Name give us identity, recognition, and a
touch of personality. So why shouldn't data
get the same treatment? Imagine calling everyone, Hey, you, it would be chaos. Data deserves the same respect. So in programming, we name our data for easy
identification. Under variables, our
data's very own name tags, variables are the
data name tags. When we are working with
the data in Python, we assign each piece
of information a name like sticking
a name tag on it. This name is called a variable. Think of it as the naming
ceremony for the data. Just like giving a pet a name, you are giving your data
a way to be recognized. For example, if you assign a value to a
random variable A, then anywhere you
say A in your code, Python knows you're talking
about that specific value. Here A is a variable. It is like saying A is 13. From now on, you can use A in your code and Python will
understand that you mean 13. If you ask to print
A, it print 13. Now there is another term
that often shows up and sometimes sounds a bit
scarier identifier. Before we move ahead
with the variables, let us understand identifiers. The fancy term for names. Don't worry. It is
simpler than it sounds. An identifier is basically any name you give
in the programs. It could be a variable, a function, or even a class. You might not aware of all these terms, but
you will learn them. For now, think of identifiers as a big umbrella term covering all the different names you
will create in your code. To sum up, remember, a variable is an identifier for a specific value
like age or height. An identifier can be a name for almost
anything in your code, variables, functions,
classes, and more. Big umbrella term covering
names for all kinds of things. In simple term, all
variables are identifiers, but not all identifiers are variables.
Picture it like this. If identifiers are
a big VIP club, variables would be one
of the cool members. Are other members too, like functions and classes, but variables are the ones
that we often start with. I hope it is clear for you. In short, naming data isn't
just about organization, it is about respect, readability, and future
proofing your code. Next time you assign
a name to a value, remember that you
are giving your data a little identity and make it easier for everyone
to understand. When you assign a
value to a variable, let us say product
sold is equal to ten. It is as if you have created
a synonym for that value. Instead of remembering
the value ten, you just remember
the term products sold and whenever you
need to update it, you just change the value
without much worry. Now I assign products
sold is equal to 20. Assigning the same variable
to different value kicks out the previous value and save the last
assigned value. Variables don't just
make your code readable. They will make it editable, manageable and way
easier to update. Previously A is assigned
with the value 13. Now I assign five. Now value 13 is
deleted for A forever. Use different variables
for different values. Variable A is synonym
with the value five. Any operations made on variable A is operated
on the value five. That means A plus one
is five plus one, which returns six and
A multiplied with three is five multiplied
with three, that is 15. This bond between
A and five will continue till value
inside A is changed. Here is another example where
naming ceremony in action. Price is equal to 10.99 units. Discount is equal to two units. Final price is equal to
price minus discount. Print final price. You asked the Python to
print the final price only hence it returns the
value of final price. Now you are not just working
with nameless numbers. You have got price
discount and final price. They tell you exactly what is happening and if prices change, you only have to tweak
it in one place. But why variables are so handy? Imagine this situation. Consider a plot of
rectangular shape with length 30 units and
breadth 20 units. You need to find the area
to provide the surface and the perimeter to put the
compound wall around them. So you know mathematics well, you calculate
mathematically, area is ten times breadth and perimeter is equal to two
times length plus breadth. You understood what I have done here because you
attend this session. But for the other person who
is using the same program, but did not see
this video session, cannot say if the
program calculates area or the total price of
30 pizzas at 20 bucks each. This is an easy example. What if the program is bit complex like scientific
and engineering problems, then you need to be ready
to get disturbed as each person who use it need to call you to understand
what this program does. Also consider the case, you need to save and reuse the value you get as the output. Like you got the local price
of the land per unit area, you need to evaluate the
price of the plot by multiplying the local price per unit area to your output area. You cannot do so as the value
of the output is not saved. To do so, you need to write the values manually
for calculations. What if there are several values need to be used in calculation? So let us make some
changes to this program. I will create two variables,
length and breadth. If you like short and sweet, you can call LNB, but I am not responsible
if you confuse them later for
lemonade and beer. Now calculate area and perimeter and we'll assign them to respective identifiers. Now I will print with a
statement the area of the plot is and add respective value to it and similarly the perimeter. What is happening here? It is simple string
addition that is concatenating the text at the
end. But is this correct? No, Python has some
problem with this program. The area and perimeter we
have calculated are integers, or depending on
the input values, they can be float
ora a numeric value. The problem is the integers and floats are not
relatives of string, and hence string is not ready to welcome the integer
in their team. Now it is the best time to use the explicit conversion that
we have learned already. First, convert the
integer to string, and now string is very
happy to accept the value. Now the program looks clean
and most probably anyone with above average
grasping power can understand what
this program is doing. If you want, you can
use the value inside the area and perimeter to
any other calculations too. Great. Take one step ahead. Let us make the
program more dynamic. Ask the user to define the
values of length and breadth. That would be more practical. The programmer usually
do not use the program, but develop them for
the different user. Use input function along with some optional
message for the user to understand enter the length of the plot and
similarly breadth. Now again comes the
problem of data types. Python consider all
the user input data as string by default. Looks like Python love string more compared to
other data types. What we shall do is convert
them into integer data type. If there are decimal parts, then make it float data type. Now program asks the user to input the value of length and breadth and the value entered is assigned to
the respective variables. User need to press
Enter with each entry. Programmer don't
have the headache of defining the values. What an easy concept. This is one way of printing
output statements. There are other ways too. You can use this format instead. Curly braces used inside the statement represents
variables and you need to define which
variable inside format in the order separated by comma. First curbras
represents area and second perimeter as
defined in the format. Inside the format,
each value must be clearly defined in the
order for a change, make the input into float. Now execute the
program and enter the value with decimal
part. Looks good. If you do not want the long tail like monkeys for these values, you can limit the decimal by specifying the
number of digits. Inside curly brace
add colon dot, which means after decimal point, F indicate limit the decimal
number of float to two. Now Python understand it need to limit the number of
decimal values to two. The output is rounded
to two decimal points. This is not the end. There is one more way to
print the output. This method may be close
friend for those who use C, C plus plus or Java. Here F represents float. There is different alphabets representing
different data types, but do not use this
method much in Python, so I will not go in details. Assigning value to identifiers make the program more
effective and useful. You are giving the identity to the data or a
function or a class. But with the power comes
the responsibility. Python has certain conditions
to select the identifiers. In the upcoming class, let us see the rules of
selecting the identifiers, meet you in the next class.
13. Rules to select identifiers: Now, it is understood
that variables or identifiers are
user defined names. I know when you are provided with the authority
to give the name, your creative self can come out with the
identifiers like these. Can you provide such identifier? Do you have all the freedom to assign any name
to the variables? Before understanding
the variables, let us analyze our names. We get better idea. Do our names are randomly
selected? I don't think so. We follow some protocol
to select our names. Do your name has special character like
Ampersand or dollar? Most likely no. Usually,
our names don't have special characters and
do not start with numbers, but sometimes may
have the numbers at the end like few
kings and emperors. Now let us come back to the main topic of rules to
select the identifiers. When we follow some
protocols for our names, then why not for the variables? If you are thinking you can assign any random names
to the variables, then I need to disappoint you. But rules are very simple and don't have
much restrictions. Here are the set of rules for
selecting the identifiers. Rule number one, do you
have any pet in your home? If not, then assume you have one as you don't need to pay
anything for imagination. Also, imagine it has
got same name as yours. I don't think anybody does it. But why? If your pet has same name as you, then
what will happen? Nothing serious will happen, but the result is confusion. You will become confused if
you are called or your pet. Same happens with Python. The first rule of selecting
the identifiers is don't use Python predefined function and keywords as identifiers. Here are the list
of Python keywords. Similarly, you have
learned few built in functions like print input type, into float, and many more. Don't keep any of these
names to your variables, otherwise, Python will confuse. Rule number two, as I
told in the beginning, our names do not have
special characters. Similarly, for identifiers, only special character
allowed is underscore. If you're allowed to
use special characters, then use it in your passwords.
It will become strong. Python allow only letters,
numbers, and underscore. Even space is not allowed. Use only underscore,
if at all you want to use any special
characters in identifiers. Rule number three, numbers
are permitted to be part of identifier doesn't mean it has freedom to sit anywhere. No much restrictions, but first character of the variable
name cannot be a number. Like front seats are
reserved for VIPs, first character is reserved
for letters and underscore. Numbers can be used
anywhere else. There is no restriction for letters and underscore position. Rule number four, identifiers take upper case and lower
case very seriously. Identifiers are case sensitive. Once you assign
the variable name, be specific of the case of identifiers when
you use them again. Both these variables
are considered as different variables because of change in case, and that's it. These are the four
conditions of variables. Here is the list of
some valid identifiers. These identifiers do not violate the rules of identifiers
hence they are valid. I know we learn what not to
do better than what to do. So for better understanding, we should go through
the invalid identifiers and why they are invalid. The first line contains
two identifiers. As per rule number three, identifiers cannot
start with the numbers. The second line,
print input, format, help, map type are examples
of Python built in functions. Similarly, the third line
contains built in keywords. Stated in rule number one, predefined functions
and keywords cannot be used as identifiers, so they become invalid. Examples in fourth and
fifth line contain space and special characters which are restricted as
per rule number two. With these examples, you have
understood what not to do, which in turn help you to learn
what to do automatically. Python is very user friendly and do not have
much restrictions. Just follow these
rules for identifiers. Python will be happy and
will not bother you. But follow a few more
rules that we explain in the next video to
make your program cleaner and more
readable. See you there.
14. Good practices of Programming: And Welcome back. In the last session, we covered the ironclad rules
of choosing identifiers. Today we are exploring
the friendlier, the good to have guidelines. The rules we have learned
in the previous session are mandatory like wearing some
cloth to job interview, and the guidelines
we are learning, think of these as style
tips for your code, like wearing a tie
or decent grooming. Sure, these tips
aren't mandatory, but they will make
your code look so much better and you will
thank yourself later. Following these guidelines
will help you write code that even a
stranger or future you, who is basically a stranger
by then can understand. Imagine your code as a
friendly conversation rather than an ancient text that need explanation. Are you ready? Here is how to make
your code clear, approachable, and even
a little charming. Good practice number one, let your code explain itself, name your variables
like you mean it. Let us be real. We
have all had those. What did I write here moments when we look back at our code. Especially if you have
used mystery names for your variables like
X and Y or A and B. Sure they are short,
but they don't tell us anything about
what they represent. Remember, the goal
of code is to be readable like a friendly
instruction manual. Let us go with a scenario. In the previous session, we were calculating
the area of rectangle. You could go with that again. How does it look or
the alternative, where we use alpha bets
and short names like this. Both work for sure, but only one is easy to read and understand without
scratching your head. The self explanatory
version instantly tells you what each part
of the code does, make it as readable as a
friendly reminder note. Then what about
mystery novel code? Well, even Sherlock home might struggle to remember what L, B and A stands for
after a few days. Give your variable names
that tell the whole story. Pick names like length
and breadth over L and B. This is your future
self thanking you. Your code becomes
so much easier to read and anyone including
you can dive in, understand, and
update it easily. Good practice number two, use comments, give your code
some friendly commentary. We all love comments on social media like
reactions or compliments, but comments in code serves
a different purpose. They are there to help
explain the thought process, the calculations, or any
tricky parts in your code. Think of commands
as little signpost. They help others
navigate your code, trust me, they will help
you to a month later. In Python, commands start
with the pound symbol. Anything that follows
pound on a line is ignored by the Python interpreter
like it is invisible. Feel free to use commands to jot down explanations,
hints or warnings. Now, don't get carried away and start leaving a
comment for every line. Imagine reading a
book with a footnote after every sentence exhausting. Instead, place
comments strategically to clarify complex parts, for instance, like this. And if you ever want to
ignore a big section of code, maybe because you're
still testing it or haven't quite
perfected it yet. You can use triple codes. Don't search your
keyboard for triple code. Use single code three times. Triple codes ignore
everything within them, making it perfect for putting
code on pause temporarily. By thoughtfully
placing comments, you give your code a
built in guidebook. It becomes understandable,
maintainable, and approachable so that different people or future you can easily pick it
up and work with it. Good practice number three,
keep things organized. Clutter free code is happy code. Just as TD desk is
easier to work at, organized code is easier
to read and debug. Keep related pieces
of code together. Use blank lines to separate logical sections and avoid cramming too many
tasks into one line. You don't need to pay anything
for leaving blank line, but don't leave
several lines blank, making the programmer search
where the next line is. Clear structure
keeps your program from looking like
a wall of words. These practices
aren't strict rules, but they are golden advice for writing cleaner,
friendlier code. When your code follows
these principles, anyone, including
you can jump in, understand what is going on, and feel confident making changes without breaking
something unintentionally. Think of these tips as
your code user manual. So keep these good
practices close. Practice the concepts
and rest up. There is more code to write, and this is just the beginning. Until next time, keep it neat, keep it readable,
and keep it fun.
15. Understanding String: Welcome to the fascinating
world of strings. If you have ever sent a text, drafted an email or
left a low note, you're already a pro
at using strings. You just didn't know it. Strings are so much more than just random text in programming. They are the lifeblood
of communication, the rock stars of data types, and the reason why
every programmer double checks their email
before hitting send. I mean, who hasn't feared
sending an awkward typo to their boss or even worse a message with that
typo to their crush. In the world of code, strings are the superstars that wear the crown of
single or double codes. Think of it as the crown jewel
of the programming world. Without it, string lose their royal status
and can cause chaos. Forget those codes and the program things you're
talking about a variable. So strings always wear
their crown with pride, whether it's single
coat or double coats, because let's face it, they need that royal flair. But why are strings
so important? Well, think about it. Every time you visit a website, order food online
or leave a review, you're working with strings. Text is everywhere, and programming needs strings
to manage all that text. Applications, websites, games,
almost every program has strings working hard
behind the scenes to make sure things look
right and sound right. Even when you input numbers, your program sees it as text
until you tell it otherwise. In the kingdom of code, string data is the
default royalty. If you are ready,
let us dive deep and dissect the
anatomy of a string. We are going to break
down what makes strings. Who knew text could be this thrilling prepared
to witness the secrets, the powers, and yes, even the occasional drama that comes with understanding
strings in programming. Just like each of us is known for our unique set
of characteristics. Strings in Python have their own identity and it's
all in their characters. Yes, a string is simply a
sequence of characters, each one holding a place in line to create
something meaningful. You can think of characters as the building
blocks of a string. Every single one counts. Even though sneaky spaces, we are creating a string, which contains, this is a string and assign this string to the
variable named statement. Want to know the
length of a string, Enter Python's magic word, Alan, which is length function, feed a string into the
Alien function and it will count every single character
and give you the total. If you try for this
particular string, you will get 16 because Python dutifully
counted each letter, space, and punctuation
mark if it was there. Don't search it here,
we don't have it. 16 characters, each one essential to make
this string meaningful. Let us talk about index, Python's unique counting style. Every character in a string
has a specific spot, which we call an index. It is like each
character is sitting in its own assigned seat and the index number tells you
exactly where that seat is. But here is where
Python gets quirky. Looks like Python had
a bad math teacher. Python starts
counting not from one like most humans
would, but from zero. Yes in Python world, zero is the starting point. For any given string, first character has
the index zero. The last character will always be at the index of
length minus one. For this particular string, length is 16 and last character has the
index 16 minus one, that is 15 simple blame it on Python's math teacher
if you find it odd. Space matters every
character's count. Don't underestimate
those spaces. They are characters too. Python doesn't ignore them. They are part of
the strings charm, so they each get their own index just like every other letter. For this string, there are three spaces which give the
clear meaning to the string. Without these spaces,
the string would be just sequence of characters
without any meaning. Now let us talk about
negative indexing, reading from the right. Here is where Python
really mixes things up. Most of the world encourages
you to be positive, Python is totally cool
with negative indexing. Instead of always
starting from the left, you can also count
the characters from the end of the string, moving from right to left. Here is how it works. The last character has
the index of minus one. The second to last
character is minus two. It goes all the way back
to the first character, which has the index
of minus length. Whether you're counting
from the start or the end, Python got you covered. Hold tight because
we are about to explore the art of poking
around inside strings. Curious about what is
at the specific index, let's pull out our
trustee magnifying class and dive into the
magic of indexing. Imagine a string is
like a row of lockers, each containing a character. Each locker has a number called index,
starting from zero. You want to know what is
hiding in locker zero, you just check string with the index in
the square bracket. Here is how it looks in action. Index zero, you unlock
the first locker and Python returns uppercase
T. If you check Index 15, you scroll down to the last
locker and it is holding a character G. Index minus one, wait, a backdoor to the
last locker, indeed. Python says, Why stop
at positive numbers? Let us count backward two. String with the index
minus one also reveals the final G. But what if
you are too greedy? Let us say you're feeling adventurous and try to
open the locker 16 in a string that only has 16 characters from
indexes zero to 15. Python is going to glare at you like a librarian when
you talk too loudly. Here is what happens. You ask for index 16 and Python snaps back
index out of range. Are trying to grab something
that doesn't exist, calm down. Think
of it like this. If your string is a
party with 16 guest, having the index zero to 15, you can't expect Python to
find a guest at seat 16. It is empty. No matter
how hard you insist, Python will not pull the
character out of thin air. You have understood
the structure and index of the string. Let us learn in the
next session to slice the strings into parts
using the index. Take a small break
and join fast.
16. String Slicing: Let us slice drink
like it's pizza night. Slicing a word that
instantly brings joy to pizza lovers and
fruit fanatics alike. Whether it's cutting into
the perfect cheesy slice or just snatching the part of the cake with the most frosting, we all love a good slice. And guess what? String
feel the same way. They're now being sliced into
smaller bite sized pieces. In programming, we call these tasty morsels from
the string as substring. Slicing is the operation that is performed not
just on the strings, but on all the sequence data
types like List and tuple. The concepts, syntax,
everything remains same. So learn string slicing. You get List and tuple
slicing for free. Are you ready? Now imagine
your string is a pizza. Instead of toppings, it
is packed with letters. You are handed a
knife. Don't worry. It is a friendly one, and you are ready to cut out
the exact slice you want. Welcome to the string
slicing in Python, the art of cutting
and serving strings, one substring at a time. Let us get to slicing. Here is your delicious
string pizza for the same string statement, which contains This is a string. Now let us use
Python's slicing knife to get exactly the
slice you crave. The syntax, it is simple
and works like magic. String name along with
start index, end index, and step size separated by
colons inside square bracket. Let us break it
down. Start index, where your slice starts. End index where your slice almost ends because
Python is a Ts. It stops at one less
than this index. Step size, how many steps you take between the characters. Want every second character, use two, want every
third, use three. Skip none, leave it
blank or use one. For example, the first
slice, let us slice up. This is a string like this. Statement with one
colon five colon two. Let us see start at index one. The character here
is H at index five, but don't include it. So we stop at index four. Step size two, we skip
every other character, so it consider the character
at index one and three. Slicing is topped at index four, five is not included. Index one has H and
Index three has es. Hence grabbing H and yes, one colon five colon
two gives us the slice Hs if any of the arguments
are not mentioned, then Python do not get Fright. It will assume the
default values without your permission. For example, if index excluded, so if you ask for
one colon five, you are really getting
everything up to four from one. Think of it as ordering pizza from slice
one to slice four. Default values are your friends. If you skip one of
the parameters, Python steps in with
some default values. Skip the start index, it start at zero. Skip the end index, it goes all the way to
the end of the string. Skip the step size, I grabs every character
that is step size is one. In first case, no
argument is mentioned, so Python need to assume
all the values by default. That is start index zero till the length of the string
in the step size of one. But what is the use
of this statement? It returns all
characters as it is. Instead of this, you could
just print a variable. This is like asking to slice the pizza and demanding
all the slices. The second line,
first two arguments, start index and end
index are provided, which has two and
eight respectively, and step size is skipped. So step size is assumed
default, that is one. If step size is one, you can skip the third
argument as it is default. No need to provide even
colons for third part. In second case, we'll
return the characters from index two till eight
minus one, that is seven. So all characters in
index 2-7 are returned. In this case, first argument, start index is not mentioned. Second argument, index
is ten, and again, third argument is missing, so it will return index from start till one less
than ten, that is nine. All characters in index
zero to nine are returned. Getting something, take
few more examples. What the code will
do in this case, here both start index and
end index are missing. Only step size is
provided that is two. The program will return
the characters from start to end in the
step size of two. That is every alternative
characters are returned. In the second line of this cell, slicing starts from
index lend till end. I hope no need to mention that
step size is two, shocked. Just checking if you're
listening or just sleeping. No, step size is one. All right slicing
wizards. Get ready. Let us go one step ahead
slicing in reverse, and now it's time to
master the backward slice. Think of it like rewinding your favorite song or moon
walking through a string. The plot twist, start index is greater than the end index
with negative step size. Here is the scene, starting
at middle of the string. End index is two
way to the left. Step size is minus one, time to move backward. What is going on? Negative
step size flips the game. Normally slicing moves
from start to end. But with minus one, we move in reverse from right to left. Python, it is clever
enough to know what you want as long as you
provide some instructions. So print statement with ten
colon two colon minus one. How this works,
start at index ten. This is the letter S move
backward to index three. Index plus one, unlike minus
one in positive steps, you grab every character until index three in
the reverse order. Output looks like this. Notice how with a
negative step size, the end index works differently. Python includes
one more character beyond the specified end index. It is like giving you free
extra slice of the cake. Do you think it is
true? Think again. Let's take it up a notch. If the start index is missing and the step
size is negative, Python thinks, you
want me to slice from very last character
back to your end index. I got it. Ask it to print statement colon colon minus
one. This is what happens. Start at the end. Python assumes the last
character, index 15, which is G. Move
backward to index six, which is end index
five plus one. Python slices everything in reverse until it
gets into index six. Output looks like this. Isn't Python very clever? Now, the big finale, reversing the entire string. Here comes the ultimate trick. Want to flip your
entire string backward, skip the start and end indices and go straight
for step size. Print statement, colon,
colon minus one. As step size is negative one, Python starts at
the last character. Move all the way to
the first character. Prints the string in reverse
order as it is minus one. Output looks like this. It is like watching
a movie backward, where a hero falls back into the burning building and
unmeds the love of their life. The golden rule, step
size cannot be zero. Now a quick word of caution. Your step size can be positive, negative, or missing,
but it can't be zero. Why? Because Python isn't going to sit there
staring at the string, wondering, should I move or not? Zero step slicing
is like trying to walk forward while
standing perfectly still. It is just not happening, so wrapping it all up. With slicing, you have unlocked the full
anatomy of strings. You have mastered the art
of controlling strings, moving forward, backward or
skipping along as you please. So go ahead, slice and dice
your string like a pro, and always remember Python
has caught your back. Even when you're
slicing in reverse. In the next video, we shall see a few methods
operated on string.
17. Methods on String: Oh Welcome back. In this video, let us learn important
methods operated on string. Shall we proceed? Let us
turn on detective mode. Find the index of a character. Earlier, we found
the character at a specific index like
playing hide and seek. But what if the table turn? What if you are the
seeker and need to find the address of a missing
character. No worries. Python's index method is your Sherlock homes solving the case of the lost child
in the string family. Let us take the string named statement that we have used
in the previous sessions. If you are looking for the
address of the character T, Python's index method
is quick to answer. The address is index zero. What about IS? Well, Python doesn't panic, even if there are duplicates. It calmly follows the first
come first sound policy. IS lives at the index two, no fighting over the
second occurrence. Got it. Good. Python is
great at finding stuff. Just don't ask it for
something that isn't there, then it throws an error. Similarly, character yes is repeated thrice in the string. But the first occurrence of
yes is at the index three. We are comparing
the string Python with string having
same characters, Python and cross checked if there is any
spelling mistake. Same characters. But when you ask Python to compare
them, it says false. Why? Because Python is a
perfectionist who judges every uppercase and
lowercase differences like a grammar teacher
marking your essay. Google search engine,
do not bother about the case of the
search you have provided. Cannot expect getting
the perfect input with the proper
cases all the time. How can I ask the Python
to ignore the case? If you need to
compare the string, ignoring the case,
then use case fold. Case fold is a liberal
valuator who do not cut the score for silly uppercase
and lowercase mistakes. It is the time to
make some changes to the cases of the string. Let me define string for
the case operations. I'm too lazy to find the
variables and string. My variable name is string and the string is example
of Python string. Why in the world
should I bother to find the identifier
and a string? Let us start the operation. The first method is capitalize. Capitalize will make
the first character E of the example to upper case, and rest will be in lower case. Observe that P of the Python has changed from
uppercase to lower case. If you do not like
to discriminate the characters and want to
treat all characters equally, use upper and lower methods. Upper will convert
all characters in the string to uppercase. If upper method is understood, then I'm very happy
to tell you that our time for explaining the
method, lower is saved. In that saved time, we
learn another method count. Do you know the meaning
of the word count? You guys are making my job easy. The method count will return the number of occurrence
of a substring. We shall use this method on the string with
the name, I mean, identifier statement to check the frequency of the substrings. It says you are repeating
the same substring like a broken record for
this number of times. In this case, it is two. To next methods ends with return true if the string contains whatever
it wants to be, but ends with a substring
mentioned as argument. This will be useful
in testing cases like if the string is
a URL or an email ID. Testing the URL, www.abc.com, if it ends with.com, and email to check if it
ends with some domainm.com. As both of these conditions are satisfied, it return true. Now tell me if you have
understood method ends with. If you have not understood, then move video a few seconds
back and see once again. If you really
understood this method, then there is no need to
explain start with earn one, get one free. Let us move on. By default, Python treat everything that is enclosed
inside code as string. It might contain alphabets, numbers, special
characters, and whatnot. Let us explore some methods that check the type of the
characters in the string. First, let me define some
strings to test the methods. As I told earlier, why we bother about identifiers, I name them accordingly. Numeric with numeric characters, Alpha, which contains
alphabets only, Alpha numeric with
combination of alphabets and numeric characters and special which contains
special characters. Now we shall see the methods
one by one. Es numeric. Check if the characters
are numeric. It returns false if string contains alphabets or
special characters. The next method is E
short name of E alphabet. That is true if characters
are among at Z or else false. Combination of Epa and
numeric is isalnum. It returns false when the string contains special
characters like ampersand, exclamatory, octothorPercent,
underscore, and so on. Turns true if the string has alphabets or
numbers or both. Do you still remember
the lesson variables? Then recall the rules
of identifiers? You can check the validity of the string that is
if it is eligible to be used as identifier using
the method, es identifier. Returns true if the string
is a valid identifier. If it violates the
rules of identifier, then it returns false. These are the test of
type of characters. Now check the cases of the
characters in a string. Es lower return true
if all the characters are in lowercase ignoring
numeric and special characters. Even a single
uppercase will change the validity of
the test to false. The sibling of this
method is E upper where the case is true if all characters
are in uppercase. These methods just check the conditions and
return true or false. If you want to convert the characters to either
uppercase or lowercase, we already learned the
methods like lower and upper. Move on to next method. The sting is messy and has
some unwanted things in it, then Python provides cleaning
tool to remove the mess. Lstrip is left handed and hence clean the leftmost
part of the string. Lstrip will check
if the left part of the string contains the unwanted things
mentioned in argument. If the case is true,
then it removes them. If argument is not
mentioned by default, lstrip removes the spaces if first characters
are white spaces. In the example, Ylstip
is provided with the argument ABC for
the string email, which has value ABC at
the red domain.com. As the email start with ABC, it removes it and return
the remaining string. If you need to clean the mess in the right or the end part, then R strip is used. This works exactly
the same as strip, but RStrip is right handed and hence hold the
sponge in the right hand. For the same email example, RStrip is provided
with domain.com. Python clean the right part
and remove domain.com. Result is left with
ABC at the right. If you need super efficient
worker who can work in both hands to clean the
mess on both the ends, use the method strip. Here, the string has
unwanted white spaces in both the ends. We shall remove
the white spaces, both at the beginning and
the end using strip method. These triplet strip brothers remove the unwanted characters, make the string trim clean
and save the storage space. Do you like to break the
unity of the string? The strings can be
broken into number of pieces using split method. Split by default
separates the string into the list at the
occurrence of space. The string in the variable
statement has four words. This is a which are
separated by spaces. By not providing any delmeter, string is cut into
four pieces at the space to make the
list of four words. If you want to split the string at any other
delimeter than space, then mention it as an
argument in this case, string is split at the
occurrence of the character S. There are three
S in the string. Hence the string is
broken at three joints, making it into four pieces. If splitting or breaking
the string is possible, then welding the string
must also be possible. The reverse case
of split is join. Join is virtual adhesive
for the string. Join connects the list of substring into one
string end to end. First, define the delimeter
that separates each element. Here is a list of
three different string and these three
words are joined end to end in the order and separated by white
space as requested. Congratulations,
string warriors. You have unlocked
the full power of string methods from cleaning, slicing and dicing to
transforming and inspecting. Go out there and conquer your strings like
the coding pro. By the way, are you
feeling overloaded? Just practice the programs regularly and apply
the concepts. You will use them
effortlessly later. See you in the next session.
18. What is Functions & Methods?: After going through all those
heavy loads of information, some or the other person would have left with one big
question unsolved. From the long time, I was using these two confusing terms,
functions and methods. What exactly is
functions and methods? Are they relatives or enemies? I mean, are they
similar or different? I thought of explaining this
concept in the first module, but I don't want to give you just the scary
definitions because definitions are by default
designed to look scary. After learning to this stage, I have a lot of examples to
explain you these two terms, it's good time to learn these
two terms to the depth. You have already met and
used many functions. The print help are all
examples of functions. We have also used
the functions for explicit conversions
like Int, STR, or float. You must have realized the importance of
functions coding. Programming without
the functions is like trying to cook without
the kitchen utensils. You end up steering the
soup with your hands. Now comes the question, who is eligible to be
called as function? Wear your seat belt, I'm going to give you the
definition of function, and I know very well that these definitions almost
always create turbulence. Here we go. Functions
are the set of instructions that
perform a task. Functions do not
change the parameter, but they return the
new version of it. Who cares those
boring definitions? Let us understand
through the example. Variable string contains
the string data, and hence, let's consider
length function. Function always start
with the function name followed by the parameter
in the parenthesis. The definition we set, it performs some task. Yes, length function find
how long the string is, not in terms of meter, but in terms of characters. Consider one example of list. We should just see
how functions work. LSD is list of some
numerical elements. I use a function sorted, and I will assign the result
to a variable sorted list. The task of this function is to sort the values in
ascending order. While defining, Sone
also said the functions do not change the parameter but return the new
version of it. You check the initial list LSD, it don't even have any clue or idea that you have sorted it. But new sorted list has got
new version of the LSD. Functions are the tools
available in Python that are always ready to serve you with love and waiting for
you to use them. They can be used anywhere in your code just by
calling their name. Now let's visit
another friend method. As usual, like everything, let's start with definition. It says, method is set of instructions
that are associated with the object that can be used only for that
specific class. I don't know why
these definitions are always scary than
they actually are. For the string, you have learned many dot notations like
capitalize upper case fold, start with, ends with, and so on till infinity. All these dot notations have the fancy name
called method. Let's take the example
of is numeric. You know very well what it does. If I use the same method
with the integer values, what will be the observations? You'll get the attribute
error with the message. It object has no
attribute is numeric. Method is racist, which is specific for particular
datatype only. That means method
of one datatype is not compatible with
the other datatype. This is what said
in the definition, methods are associated with the object that can be used
only for that specific class. Dot notations of string will not available for
other datatypes. Let us see why the term class is used here in the OOP session. Don't worry much about it. You will understand that later. As of now, it's good enough. I hope you have
understood the difference between the functions
and the method. Let's forget methods for few moments and
concentrate on functions. Only for a few moments,
not permanently. Built in functions are baked in the restaurant
of Python for you. You just need to go to
the Python restaurant and order any function you need. But sometimes the
dish you are looking for is not readily available
in the Python restaurant, no, online order
will not work here. That is the situation where you need to cook
your own functions. Such functions prepared by yourself are called
user defined functions. Are you exited for
the cooking session? See you in the kitchen.
19. Defining Function: Till now, we have mastered
many Python built in functions,
especially on string. Python has several
built in functions, serving various use
cases and tasks. Some of them we
have already went through and some of them
we are yet to explore. But these functions might not be able to solve all
our required tasks. We cannot expect everything
as per our requirement. What we shall do in such cases. In the ancient days, humans use stones and
sticks for hunting. But is there sufficient for
all situations of hunting? No. When the existing
tools are not efficient and sufficient
to fulfill our needs, humans used existing tools to prepare arrows and
other sharp tools, which made our
work a lot easier. When we do not
have what we need, use what we have as
the raw material and create the
customized product. That quality made humans
unique among living organisms. Similarly, we define
the functions as per our requirement
when we don't have one. Such customized functions are called user defined functions. User defined functions
is similar to teaching new recipe
to the Python using the ingredients we have
so that it prepares for us whenever we want
as per our instruction. Let us say, we need to calculate
the area of the circle. We don't have any ready
functions to do that, so we are teaching the
Python this new recipe. Type def. No, Python is not def, but it is the short
form of define DAF. This is like telling the
Python, Hey, Python, the built in functions you have provided will not
enough for my task. I want to define
my own function. Python says, Okay, go ahead. But what is the name
of your function and what input you need? Now provide the name
of the function that is understandable along
with the input parameter. Recall the rules of
selecting identifier. As name of the function
is also an identifier. Rules are valid here. Accordingly, I name
my recipe area of circle separated
by underscore, as identifiers dislike space. To calculate the
area of the circle, the required parameter
is one that is radius. You have defined the
name of new recipe and also required ingredients are also listed in the
form of parameters. What's next? To bake
and prepare the recipe. Start giving instructions
how to bake. As all the code I'll be
writing hereafter belongs to this function that is explaining how to
prepare new recipe, provide a colon telling Python
continuation of this task. Now you can observe
indents have been moved. Once this function is defined, you just come out of
this mode indents to end the function that
we shall see later. Now provide the expression to calculate the area
of the circle. Area is equal to pi
times radius squirre. Now our recipe is prepared and we need to present
the prepared recipe. What is the output
of this function? It's area. Return area. As you provided
written statement, Python understand that your
cooking session has ended. I mean, the function has ended. Hence indents moved back. Now your function is defined. What shall we do
with this function? It did not return any output
even after executing it. No program know what to do. What it don't have
is input value, the radius of the circle. How can it return output
without input value? No ingredient or recipe. You have just taught the Python how to prepare the new recipe, if you want the Python to
cook as per your instruction, you need to order it to do
so by giving the ingredient. Now calculate area using the function by just
providing the radius, which is the only and main
ingredient of this recipe. Now you've got the output. This is an example of single parameter,
single output function. You can define multiple
parameters and multiple output, like in previous example of area and perimeter of rectangle. This recipe has two ingredients, length and breadth, unlike one ingredient in
area of circle. Ingredient list is
separated by comma. Using length and breadth, we make area and perimeter. Recipe has two outputs, written both area and perimeter. Both parameter and output need
to be separated by comma. This recipe is taught
to the Python. Now use the defined function and provide with
length and breadth. You get two output, 601 hundred. This is always in order we
provide in written statement, area followed by perimeter. In function, you define the rules once and use
it multiple times. The output need not
be written always. It can also be print statement. The same example, function
to calculate area and perimeter of rectangle is written with the
print statement. Output looks similar. Both this written
and print statement give the same or
similar looking output, but they are different. Print statement
display the output, but its value cannot be saved or stored or further used
for calculations. As written gives value
that can be assigned to the variable and can be used for the further calculation
like we did in this case. Area and perimeter are calculated
for provided length and breadth and resulting values are assigned to two variables. That cannot be done when
there is print statement. Hope you have got the difference between print and return. In the next video,
we shall explore a few examples of
functions. See you there.
20. Examples of functions: In the previous lesson, the concepts of user defined
function are discussed. When we need to program
the routine task, we can use functions as they can be built once and
used multiple times. In this unit, we shall
see a few functions so that you will understand the concepts of
functions better. Functions can be as
simple as this example. Greet which take the name as input and print the statement
hello with the name. Now use the function with
the name here, John. Look at another example, Celsius to farnate as
the name suggests, the function for the
temperature conversion from Celsius to fnate. First step, give
a beautiful name for your dish and
mention the ingredient. I define function name with the temperature in
Celsius as the input. Do you remember the
formula for conversion? If not, Google it or ask ha GBT. They are the only
teachers who can help you at anytime
with any problems. Let's come back to our formula. It is temperature infarnate
is equal to temperature in Celsius multiplied
with 1.8 and add 32. Now return temperature infarnate
which is our end result. Now I use function Celsius to farnate with 25 degrees
Celsius as input, which is translated
to 77 degrees farne. Let us make the
program more dynamic. I'm not entering the value here. I'll get the input from the
user and convert it to float. Now enter the value as a user. It returns the
converted temperature. But we are experiencing a
long decimal part here. If you want to restrict the
number of decimal points, add round function in
written statement. As the name suggests,
it round off the values and I'll be limiting the decimal
values here to two. Use round function
whenever you like to have. Now let us run the
program again. We got it. Isn't it cool? Learn the concepts of user
defined function well. We are ending the model here, but our friendship with the
functions will not end here. It will continue till the
end of programming journey. Every now and then
they will appear. We use them very
frequently in programming. Even you get your hands into various functions
of your liking. Create functions to solve
your day to day task. You will get practice easily. Also, it will help you
to program efficiently. Now we shall take some rest and meet again in
the next module.
21. Conditionals and Branching: Do you still remember
the comparison operator? Congratulations. You
don't need to watch it again before going
through this module. There we have compared
the values to get the result in terms
of true or false. What we should do
with true or false? Even kids will answer
that, true or false. We need to make some decision based on the result
of comparison. That's how we make decision
in day to day life. What if the day is rainy? If it's true, carry umbrella
when you go outside. Else, if the day is sunny
carry protective eyeglasses. We make this I and s analysis. Now bring them to
the programming and apply them to
an example now. This is a program that will
decide what gift you get to go to college based on the
score you got on exams. Let us provide their
score they got on exam. If they want, add the statement like
enter your exam score. Now put the
conditional statement. If score is greater than 90, as discussed in the
previous module, this statement has not ended, so provide Colon saying, Python, hold my seat, my journey will continue
in the next line. So if your score is 90, you get car to go to college. Assume you are a rich kid. Now, what if this condition is false and kids
score less than 90? We have a backup
dancer in the party. If the first answer, I mean, condition is true,
then it is great. We can make them
dance in the party. But if they did not turn
up and answer is false, we shall have the backup dancer in the form of ALIF and s, who is the last option. We shall see them now, ALIF, which is the short name of s if score is above
80 and below 90. As above 90 is screened in
the previous statement, I don't define the
statement greater than 90. Otherwise, you include
the statement. Here it is not necessary. If value is above 90, who is the main dancer? The code neglect
all the other part because they are just
brought as backup. The program will
conclude by executing the first function and directly
come out of if statement. Let us come back to
our second condition. If score is above 80, you get a motorcycle. Not bad. But what if the
score is still less? If score is below
80 and above 70, the gift is bicycle. If you want to save
enronment, score 70-80. Come to the last case, se, we are using se here, not F because this is the last backup dancer and we don't have any
other backup now. So we use se instead of LIF
as it is the last condition. If score is below 70, you get nice pair of
footwear so that you can walk or take public
transport to go to college. If you want to stay healthy
and fit, score below 80. Do it at your own risk because these conditions
may not apply to you. Don't tell me your
dad did not gift card to you despite
scoring 90 plus. Even my dad didn't. Just like the conditions, the output can print something
or return some values. If you need to use the same
program multiple times, bring them inside a function. We shall use that right now. I include these conditional statements within the function. Say decide gift is the name of the function and exam
score as argument. Everything else remains now use the function
to get the output. Conditionals can be used
independently without functions. With the conditionals,
the user defined function get more
power and versatility. For some use cases, IL statement can also
be used in single line. If you are lazy, then might
have excited to learn how. Then stop this video and jump
into the next one quickly.
22. Examples of Conditionals: A we shall see a few
conditional examples. First, we start with very simple examples of
conditions within the function. It is a function that find
if the value is even. As usual, I define the function, DEF is even with the
number as parameter, and now experience
the beauty of Python. Next one single line will
take you to the climax. Return true if
number modulo two, which means the remainder
when number is divided by two is equal to zero, se false. Python understand
human like language. Test few more cases. Here you can see
the close relative of the previous function, which written if the
number is odd or even. Only difference is earlier
output is Boolean. Now it is the
string, odd or even. Write function name
with a argument. Then written even if
number mod two is zero, se odd. Why always numbers? String will be angry, and we treat everyone equally. Time to take string as an
example now for argument. Say there is some
statement like this. Python is a
programming language. Nothing new. This statement
is an already known fact. User want to know if there is a particular keyword
in it, say Python. Define the function with string and substring
as argument. Return true if substring
is in string, Ls false. This statement literally
feels like human language. Even someone who do
not know programming, but know English can
understand these lines. Make some modification
to the substring now, making P to the lowercase. But remember, the string
is case sensitive. If Python is in lower case, the story is different. If you don't want to
be case sensitive, use case fold method that
we have discussed in the string module.
Now last example. All this example we have
taken are written statement. Print statement
will feel bad as we are using the written
for all the examples. Here is your example,
print statement. This is a simple program that return if trade is
profit or loss, along with the value based on bought price and sold price. Define name
accordingly, along with bought price and sold
price as arguments. Now, outcome is defined based
on which value is higher. If bought price is
greater than sold price, outcome is loss, otherwise,
outcome is profit. Now comes the print statement, which print the outcome along with the value of
profit or loss. Value is found by the difference between the bought and sold. But here the value is surrounded by several layer of parenthesis. What a tight security for difference between
bought and sold. Let us understand
them layer by layer. Start reading from inside. First, we need to
calculate the difference between bought and
sold in both case, whether it is profit or loss. But if the bought
price is lower, the value will be negative
because it's loss. As we have the outcome
printed separately, and hence we need to ignore the sign of values
and take absolute. If the value is negative, it return as positive value. If it is a positive, absolute has nothing to do. I can chill. Once Absolute
has done its work, value is converted to string so that it can be
added with other strings. Here, dollar is used
as a currency symbol. Add whatever you want if your keyword allows
you to do so. Now continue statement with outcome which has
value, profit or loss. Now function is ready to use. Great. Oh, forgot to check. Are you still with
me or sleeping? I understand. I will end the lesson and give you free time to really
take rest now.
23. Loops: Have you ever felt bad doing the similar routine
task every day? Most of the professionals do the same or similar
things every day, which we the humans feel
mundane after a few months. Computer is better at doing such task because
it is a machine, do not have any emotion
and never feel frustrated. Hence, it can do same
boring task million times without complaining. The loop is the term used
for repetitive task. We all have experienced such routine mundane
repetitive task. In programming that is
achieved using loops. Loop is a set of
instruction that continue to execute repeatedly till
some condition is violated. Let us make it simple
to understand. It simply means loop
is a strict pause who do not leave you till
the task given is done. Loop is programming version
of your school exam. There is no escape from it
till the exam is passed. Till then repeat
the same procedure. Now let us find real world
programming example of loops. Do you know ATM machine? Sorry, I know it is
a wrong question. Who don't love the machine that gives money? How does it work? First step, user enters
the amount he needed. Now system enters into
a loop and in each loop it returns currency and value is added to total
amount collected. Machine keep on to
dispense the currency till the total sum reach
the amount requested. Once the amount is
equal to requested sum, machine comes out of the loop and release the currency
to the customer. Did you understand the
concept of loop or entered the loop of doubts and
questions? Don't worry. By the end of this module, you will come out of
that loop of confusion. There are two types of
loops used in programming, I loop and for loop. Imagine you are making sandwiches
to your entire family. I'm sure you will
not keep on making hundreds and thousands of
sandwich, preparing whole day. There must be an end to your
task preparing sandwiches. There are two types
of end to this task. Number one, you must stop making sandwich when all the bread
you have are exhausted. Second type of end
is when you have made enough sandwich that
all member of your family, including you are satisfied. The first case is for loop. In that case, based on the
number of bread you have, you know how much sandwich
you are going to prepare. The second case is i loop. In yoop case, we cannot calculate how much sandwich
you need to prepare. Someone may have one,
some might take three. You need to keep on preparing till everyone
had enough they want. This is silly difference
between for loop and i loop. We shall see them in
detail in next video.
24. For Loop: Now it is understood
that loop keep on executing same set of instructions for
multiple iterations. Statement sounds good, but the term multiple
iteration is very general. Precisely, how much iteration
is that multiple iteration? For some use cases, we know how much
iterations program should go through the loops. In some cases, we do not
know the exact number, but keep on executing until certain
condition is violated. There are two types
of use cases. If you or the program know
the answer for this question, number of iterations, then
such use case is four loop. Before you join the college, you know how many
years you need to pass to complete your degree. Similarly in for loop, program no the number of
iterations it goes through. You will use the four
loop in your kitchen too. Imagine you are a chef and
need to peel the potato. You pick one potato in each
iteration and peel it. Then you go for the next potato. Before you start peeling, you know how much
potato you need to peel and in each iteration, you know how much is left. I assume your concept
of four loop is clear. Of introduction, we shall
see the four loop in action. Here is the simple example of how to define the four
loop using the range. Define the range by mentioning start and step
size of the range. I hope these terms are not
strange for you if you have learned the string
properly. Aren't you happy? Your old friends were back? Like in string, if you miss any argument among
start and step size, program assume the
default value, but the last value of the
range is strictly defined. When you are informed that your chef has peeled
four potatoes, then you start
counting from five. But when you don't have
any such information, you start from
beginning that is one. But for Python, start is zero. Hence for Python by default, range start from zero
in the step size of one till the last
value minus one. The range five indicates 0-4, that is N minus one
or five minus one, which is four in the
step size of one. Range five is zero, one, two, three, and four. Is assigned to I
in each iteration. Nothing complicated here. We are taught or learn to
make things complicated. Just like you pick one
potato each time to peel, loop take one value in
order and enter the loop. That is, in first iteration, I is assigned zero and with
the value, I enters the loop. In next iteration, I is
assigned with value one. Now the program says, I understood what are the values with which I need to iterate. Now tell me what I need
to do in each iteration. It is the time to
give the instructions what to do with the range. Example, here, print I squared. If you execute this, in
the first iteration, value I is assigned with zero, it calculates I squared, print the value, and
go to next iteration. That continues till the last
value of I, that is four. Once all the
potatoes are peeled, program comes out of the loop, you are left with a set of peeled potatoes
that is I squared. The peeled potatoes looks like this result of the square
of range zero to five. Do not like the plane output, you can add statement like
square of the value is this. In this example,
start of the range is not defined and hence by
default, it assumes zero. Now we shall define the range
which start not from zero. I will define five to ten. Someone has already
peeled four potatoes. Hence, you need to
start from five. Now can you think of the values
that goes into the loop? It is five, six, seven, eight, and nine, but not ten. I will not make any
changes to the value and print the values
as it is, print X. It is very simple example. Now climb one more step. Now define the range
with the step size. In the previous module, while understanding
the functions, we have defined function for Celsius to farent conversion. Now I bring the
reverse case here, farnet to Celsius conversion
for the next code. Temperature in Celsius is equal to temperature in farnet -32, whole divided by 1.8. Return temperature in degrees Celsius rounded to
two decimal points. Now function for our
calculation is ready. Come back to the four loop. I am defining a range from -50 to 50 with a step size of ten. If second argument is 50, the range will end at 40. If you need to include 50, you can define 51 instead. Now print the value of degree Fahrenheit and
corresponding degree Celsius using the functions. Here, output is calculated
not for one particular value, but for multiple input values, and users do not have the hassle of providing several
values to the function. We are pampering numbers so much that string
might feel jealous. In the next example, consider the letters in string Python. For letter in string carries each character to the
loop in each iteration. I will print the
characters one by one. This is a simple
example of the string. We shall try the four loop
with data structure like list. As the first step,
define the list. If you do not understand
what this list is, then don't scratch head. Going to learn about them in
detail in the next module. Here we provide the list
for the iteration using the statement for
fruit in fruits. Fruit is variable assigned
to each iteration, and fruits is the
name of the list. In each iteration,
one element of the list in order is
carried into the loop. I will print some
statement which sounds similar like I love and
add variable fruit. I don't know which
fruit you don't like because neither I
know you personally, nor I am a mind reader. Let us assume you hit pineapple. I add the statement
if X is equal to pineapple in the next line,
adding keyword continue. What it does is it skips the print statement if
fruit is pineapple, otherwise, print as usual. There is one more
similar keyword, break. Using the break in the loop
is similar as continue, but break will stop the iteration when some
condition is satisfied. When the condition is met, loop will be upset and
will not continue further. In previous example of fruits, if the fruit is pineapple, continue will skip the pineapple and continue with
the other fruits. Break is used, programs
stop consuming fruit when it find pineapple
and the loop stop iterating, we shall see the example of
using break in programs. We use electronic gadgets which are protected
by the password. The gadgets ask to re enter when the password is wrong till
maximum attempt is reached. It is an example of a loop. Once you enter the correct
password, it breaks the loop. Now we try to understand what is happening
in this example. First, I define the
actual password. I know password cannot
be displayed so openly, but it is just an example
and here we are just understanding the concept and do not think this
is my password. I'm smart enough not to
keep this simple password. Define the conditions.
I define range five because five is the
maximum attempt for this case. Ask the user to
enter the password using the input and
get attempt password. If password entered is correct, then interface should print correct password
and break the loop. Here, break is important. Otherwise, program asked
to enter the password five times even if the
password is correct. If the password is correct, this loop is to be broken. Else inside this, there
is one more condition. If I is four, that means the fifth attempt
as I starts from zero. Give the message that
attempt has exhausted. Otherwise, ask to enter
the password again. That is simple to understand. We shall execute the program. Test the program
for the use cases. First attempt
failed, tried again, and in the third attempt, I entered the correct password. Program now don't ask me to
enter the password again. Great. Let us go one step
forward in for loop. It is time to use
loop within the loop, which is called nested loop, but we shall see
them in next video.
25. Nested For Loop: Nested loop is like
onion of loops. Once you break the first
layer, you have a surprise. You have one more layer. As a beginner, if you see
several layer nested loops, it will cause headache. Hence, we try with two
layer nested for loop. First, we shall
understand the use case. Here I'm making list of all possible
tournament match pairs among the teams for being
unbiased and easy availability. Have named team as ABCD, E and F. We have full freedom to name
the team as you want. No one will ask us and also
do not ask me which game. Again, I give you the freedom. You can assume any game
that is up to you. I have defined the team's name. This type of collection
of data is called list. Now start the first for
look for Team one in teams. It will select one
team in one iteration, starting with first team. Now we need to select one more team to play
against the first. Hence, we use the nested
for loop to select the second team holding
the first team in hand. Team two in teams. Now comes the condition. There are two conditions. First, as nested for loop, do not know that
we are selecting the two different team to
play against one another. It will select the
same team twice. Team two should not
be same as Team one. Simple logic. They cannot
play against themselves. Second, once a pair is formed, that pair should not repeat. What that means is once pair, for example, A and B is formed, then no need of another pair, B and A. I will target both these conditions
in one statement. That is index of Team two should be strictly
greater than team one. When it is strictly
greater than, there is no
possibility of having the same index and it won't repeat the previously
formed pairs. Now print Team one
versus Team two. That's cool. Such type of four loop inside
another four loop is called nested four loop. Now we shall see one more example that was
nightmare of our childhood. Do you remember the
multiplication table? Using the nested four loop, we can create the tables in just four to five lines of
codes. Are you excited? To create tables, we need two
values in each iteration, and third is the
product of first two. Hence, we define 24
loops, first four loop, for I in range 126, I'm creating a small table
till five multiplied with pi. If you want, you
can make larger, but the logic remains same. Second, similar for loop
for J in range 126. There are two values I and J. Print in the format of tables. I and multiplication
symbol, I use X, and value in J is equal to
the product of I and J. In format, mention I, J and value we get when
I is multiplied with J. After one set of J iteration, let's have one blank
line for better looking. That's it. We are done
with coding the tables. Execute this code. You table is ready to serve. Interesting. You might have understood the importance
of nested for loop. It makes your complicated
codes very easy. Let us say meet you
soon to the for loop. If you find for loop
easy and interesting, then you will feel it
easier with the Y loop too.
26. While Loop: In for loop, the number
of iterations is known based on the range or
the elements of sequence. Met new friend yoop. I loop is like dancing in the party which has
no time restriction. You will continue to
dance till either you feel tired or guests in
the party start leaving. In yoop, iteration is
based on some condition. Here is a programming example. Let us start the i party. Now the first song is being
played for you to dance. I will assign the value
one to a variable X. Let us say you will
be exhausted after dancing for six songs,
that is your limit. I want to set the value of X. The number of song that is
played is set less than six. Write that in the language of Python as while X
is less than six, I will give some operation here, say your tiredness gets squared with each
song you dance for. Square the value of X
like we did in Flo. Let me explain what the
program will do now. Python know the
value of X is one. Y loop will check if the
value of X is less than six. Unless computer has any
learning disability, value of X that is
one is less than six. As this condition is true, the loop is entered for
the first iteration. As per the instruction
in the body, program print square of
X that is square of one. That ends the first
iteration of loop. Now the program goes back to the Y loop condition and check if the condition
is true again. The value of X remains one as the party organizers won't come and update the song number, which always remain
less than six. Did you observe an
important thing here? This condition is true forever unless the
value of X is changed. As this condition never
changed by itself, the program keep on executing
infinite number of times, wasting the resources, and
finally hang your computer. That is the reason y loop is bit dangerous as number of
iterations are not defined. How can a value change itself? No, it won't change itself. They always need a
statement inside the Y loop to change the
condition that y loop checks. Here we shall add one value
to X in each iteration. That is X is equal
to X plus one. In first iteration, X is one. At the end of first iteration, X is incremented by one unit. When I loop condition is checked for the
second iteration, the value of X is two. At the end of each iteration, the value of X is
increased by one unit. Now there is a situation
where X is equal to six, which violates the condition and the far loop stop iterating. Now execute the program. Perfect. Infinite loop is
the major concern of Y loop. Now look at this
senseless program. This condition has the
statement to change the values that is X is
increased by one value. Still, X will always
be above zero. Here also program always remain true and hence it
cause infinite loop. Just make sure while program, ilop will not end up
with the infinite loop. Otherwise, you need to keep on dancing day and
night without break. Now let us see how we should
deal with the string. As the first step, I will define the string Python to
a variable string. Let me explain the use case. What I'm doing here
is I will print each character separately
like we did in for loop. We shall define the index, which is initially set as zero. As index cannot be greater
than the length of the string, I will define while index is less than
the length of string. Now print letter include the index in the format
of index plus one. As we don't count the character
from zero like Python. Along with that,
print the character of the string in that index. Now important part,
give increment to the index before it
reiterates to the loop. If you do not know it,
index plus is equal to one is same as index is
equal to index plus one. Program is ready to execute. Looks good. We shall look at the example of how
to deal with the list. Here is a list of numbers
and in the current example, we shall develop the program to compute the
average of the list. Define the variable index
and assign the value zero to it and create
another variable, say total, which is also
assigned with the value zero. To add and store any
ingredient in the box, the box should be first empty. Hence, the index and total are assigned with the value
zero to make them empty. Oh, why no one has told me yet. I cannot use the name list for the variable as list is a
predefined keyword in Python, if I need to use the name
list as the name for a list, I need to misspell it LSD. Now I don't have the hassle
of finding the new variable. Now comes the Wiloop condition. While index is less than
the length of the list, this statement ensures
that all elements of the list went through our
Wile loop security check. Write the code for
the body of the loop, find the sum of all the
elements of the list. Total is equal to the
value of total in the previous iteration
plus element in the index. Now important part that we have to remember for the
Y loop example, increment the value
of index by one. In first iteration,
total is zero, which get the first
element added to it. In each iteration, total adds the one value
of element to it. Once it completes all iteration, total get added with all the element which makes
it sum of all the element, as its name suggests. Now comes the climax, calculating the average
using the total. The average is equal to total divided by the
length of the list. Program is set, you can execute. Hope now you have understood
the difference and application of
While and for loop. In the for loop, you have seen the application of break
and continue functions. While loop entertain
break and continue functions just like for loop. I know just mentioning
will not help you. To understand the concepts,
you need examples. Here is an example
of break function. As functioning is same as
the one we used earlier, I don't repeat it like
the broken record. I plus equal to one is same
as I is equal to I plus one. Similarly, try with the continued function
and get the answer. If it is same as you guessed, I assume your concept is clear. That's interesting. Loops are important part of programming. Hence, practice it more to become confident in programming. For now, take rest and let's
meet in the next module.
27. List: I hope you're enjoying the
journey of learning so far. Most of the concepts
you have learned so far are so easy and similar to the ones you have
learned in your schools that bring you the memories
of early school days. Let us now go through another
primary school concept. When I said primary
school concept, I'm sure you are filled
with the enthusiasm and excitement along with
your old memories. When we were kids, we had these type of questions
asked in the exams. List A five fruits, list any four mammals, simple quotiens for
which we used to write few examples of members
belonging to that category. Now we shall learn same
concepts in programming terms. List, as its name suggests, is group or set of data
assigned to a single variable. The elements of list
are included inside the square bracket and
are separated by comma. Here are some examples
of defining the list. List is not stranger for us. We have met list earlier
in various models, but we could not get the complete introduction
of the list. It is the time to
know about the list. The first list fruits,
as its name speaks, everything is the list of fruits where elements
are of string data type. Primary number is a list with elements belonging to
integer data types. Class core is a list
of marks scored by kids of the class,
which is floats. Don't ask me if the class
has strength of only four. This is for understanding. If you have time and patience, fill the score of whole class. What we can observe
here from this example, user has all the freedom to use elements of any data
types in the list. There can be string, numeric, even mixture of
different data types, and also can be list. This list of list is
called as nested list. Did you take the notes on the operations performed
on the string? If yes, your effort
has reduced a lot. Go through them once and recall. Most of the operations
we performed on string are free
with the list too. But why operations of string have few
common with the list? Because they are
close relatives. Just remember one
common relationship between string and the list. String is the collection
or sequence of characters and list is the collection or
sequence of elements. This similarity makes
the few operations common between string and list. Which are those operations that are common for list and string? It is the right time to
explore some of them. First example is length. In string length function LEN returns the number of
characters in the string. The same alien
function is used in the list which return the
number of elements in the list. Next operation that comes
free for the list along with the string is adding
two or more string, which concatenate, that
means joins them end to end. Similarly, adding two list will join the
elements end to end. The other common
operations between string and list are indexing
and slicing. In list, the concept of
indexing and slicing will be same and hence I will not waste your time by
repeating the same things. But look at these examples. You will understand how to
use them in list better. Slicing is easy for list once
you understand the string, but list comes with some twist. Do you remember
about nested list? We just said, excess
in data might seem a bit confusing for the
nested list, but it is not. Excess the element
using two indices. For example, list zero, one, which are included
in two separate brackets. Let us understand
this with splitting. First, we select zeroth element or which is the first
element in human language, which is, again, the list. To further explore, I provide the index of the nested
list in separate bracket. So I'm accessing the
element in the position, having the index one. Isn't it simple? It is
simple and straightforward. Okay, we saw the similarity
of list with the string. They are relatives but
not identical twins. There is one major
difference between operations on string and list. That difference is list
is mutable over string. I know that word
don't sound cool, but its meaning is very simple. List is very flexible. It just means that
you can add, modify, and remove the element
in the list where the characters of the
string cannot be modified. We can only assign a new
string to the same variable. Let us explore those
mutation advantages available for the list. Take the fruits list. Some lazy fellow has added
only few names to the list. Now the same lazy fellow
will add few more elements. I use append function. Append function is
the security at the entrance who allows permitted person to
go inside the list. Append will add the
new member at the end. I have run the line
twice by mistake. Hence mango is also added twice. Mistakes teach us many things. Even with the mistake, we can observe and understand
one thing here. List can accommodate duplicates. A pen has a bad habit, not really bad, but we
can say limitation. Even if the new element
fruit you added, mango is your favorite one. Python give last priority
to the new element. It gives first
priority to seniors. To add the element
to a specific index, we have insert function
which takes two arguments, one index and second element. Element is added at the
specified index and move the other elements on
the right side by one index. What if the specified index is greater than the maximum
available index? I know you get such
creative questions. Simple, it adds to the end. Opposite is also true. When specified index is smaller
than the minimum index, it add to the beginning. Right to add the
element also gives you the privilege of right to remove the element using
the remove function. Remove function need
element as argument. You can also remove elements using the index of the element. To remove the element
based on the index, pop function is useful. I removed one mango,
remove function, take element as argument
and pop take index. When pop don't have argument, it remove last element. Pop does one more job. While it removes the element, it returns the value.
What does that mean? Simple. Element kicked out of the list using pop function can be assigned to a variable. Now let's explore
ordering method in list. As I told in the beginning, Python is so beginner friendly that anyone can say
what a function does. Here are a few examples. You can see two
functions used here. One is reverse and
one more is SAT. Both of these are well
known English words, so I hope you know the
meaning of them already. Just guess what they
do to the list. Guess it correctly. Thanks
for making my job easy. You can compare the
result before and after. That is made directly
in the next lesson.
28. List Comprehension: In the previous lesson, we saw list that is defined by the user by entering
the elements manually. If the list is large, it is quite difficult to define. Moreover, we are lazy that we always find some easy
way to do the task. Python know we are lazy to
even enter the elements. Hence Python can create the
list with the elements for us if the elements are
based on some rules. If you want to create the list that are following some pattern, tell Python what you want as element in list
and its condition, Python will make
the list for you. We can define the list by giving the instruction that
Python can understand. The statement must
include what to do for what values and what's the
condition if there is any. Here is an example.
First, what to do. The instruction says to
create a list of squares. Now comes the second part. Okay, we shall create
the list of squares, but we can't create it from
zero to million, right? Then for what values? This part says for I
in range zero to ten. Is there any condition along
with this instruction? Yes, consider only odd numbers. I I modulo two is equal to one. When divided by I,
if reminder is one, then it is odd number. If your instruction
has completed, then close the bracket. The condition part is optional. Here is one more example. X for X in range zero to 50. If X modulo four
is equal to zero, and X modulo six
is equal to zero. That means divisible by
four and divisible by six. This example has two conditions
combined by and operator. Hence, if both conditions
are satisfied, then you get the value in the
list, otherwise, skipped. We treat everyone equal. Next example will be for string. Letter for letters in Python. Here, the four loop, it reads through
the characters of Python and add them to the list. This method is efficient
when the instructions are simple and could be
defined in one single line, like what are your favorite
toppings for the pizza? When your pizza is to be
customized as per your liking, that cannot be explained
in one single line. We need to create an
empty list and append the values to the list
based on the instructions. Shall discuss this
automated development and modification of existing
list in the next session.
29. Automated List: We all dreamt of having
the character like Ginni from Aladin
in our real life. Who could do all
the work for us. But later we accepted
the reality. That is not practical, but it is practical to automate our programming task in Python. One such thing Python can do for us is it can create the
customized list for us. Let us understand the
automated creation of list based on the instruction
using an example. In this program,
creating the list of all the prime numbers till
the provided number say N, it is difficult to define it in one single line like
in previous session. There are multiple ways you can achieve the
problem statement, so you can try your own method. I will be writing the
program in two phase, first, developing the function to
check the prime numbers, and in second phase, creating
the list of prime numbers. I will start the phase one program to check
the prime number. Name of the recipe is E prime and ingredient is one
that is say number. Step one of phase one. Let us neglect all the
values less than one, zero and negative numbers. If that is the case,
written falls. Now test of primality is checked for all the
number above two. I assume you have
learned in school that the primality is tested only
till square root of number. Square root is rounded to
the next integer plus one is because for loop neglect the last value and consider
till last but one. With the value assigned
to I enter into loop. If I divide the number, then the value is not
prime, hence return false. If the number has defeated
all the conditions above, then it is a prime number
and hence return true. Now the phase one, developing
the function has completed, and I'm testing the function
for random number 99. Got the obvious answer. False. It is not prime. Now second phase, developing
the list of prime, creating the function
print prime, till the value N, create an empty list for the
Python to fill the elements. Prime numbers in the list
must start from two till the value N. The value N
might also be a prime number, which will be neglected
by four loop, hence considered
till N plus one. In the previous
developed function, test if the iteration
value a prime. If it is a prime we are searching for, then
do not leave it. Put it into your
basket by appending. If not, let it go. Once all the iteration
is completed, basket is filled with
the prime numbers. Return the prime list. Phase two is also completed. Now I'm taking the input N from the user till which the
prime number will print. Now execute the function. You can also modify the
list using instruction. Here is a list of Email IDs belonging to some employees
of an organization. We need to update the Emil IDs with the new domain name
of the organization. Don't ask me why we are not poking nose in organizations
internal matter. You can assume organization
has merged or anything, I have given you the freedom. What we are supposed to do is replace the old domain
with new domain. Name remains same.
Create an empty list to fill new email ID. I read through each
element in old email list. Replace the old domain
with new domain and append the new email to
the list. That's it. Your work is done. Print the new email list. These are the methods
by which you can create and modify the list
using the instructions. I hope you enjoyed it. You can save a lot of time and effort of creating the list. That is something we the
lazy beings love to have. But there are use cases where
user must create the list, how to get input
list from the user. We shall discuss that, but take a break and join the
next lesson. Be quick. Don't take more than
10 minutes break. Otherwise, I won't allow
you inside the glass, but you can apend
yourself inside the next session. See you there.
30. User Defined List: Now you know how programmer
defined the list and Python create the list
based on the instructions. But in some use cases, user must have the authority
to define the list. It's time to see an easy
but very useful syntax for coding that is
user defined list. I don't want to give you a
brief introductory speech on the topic at the end of
which you agree what I said, but knowing or learning nothing. Let us learn this with an
example which help you better. You are now very familiar
with the input statement. Earlier, we use the
input statement to read a single value, which are assigned to
separate variables. Now it's time to push the
limit of the input statement. Now we shall assign a list
of values to a variable. First, understand the use case. Nothing complicated,
a new version of the old concept you
have learned already. What the example will do now is ask the user to enter
the multiple values. In other words, user defined
list separated by space. The problem statement is finding the average value of the user
defined list. That's it. As user defined list is the
highlight of this story, let us keep it as climax. Now story begins. Recall, in the Y loop session, we have created a program that calculates the
average of the list. Based on the same concept, we create a function to return the average but using for loop. Find the function average with a list named group as the input. Create a variable
total and assign zero. In four loop, no need
to define the index. For easy calculation, I
will find the length of the list and assign to separate
variable for I in group, which take each element in the list group into the
loop in each iteration. And add the value of the
element to the total. In the next line,
move the indens back, which gives the message to the Python that
this part need to be executed only after the for loop iteration
get completed. Once the iterations are done, total is sum of all the
elements in the list. Using the total, calculate the average and
return the value. Now function is ready. Jump into the main part of
getting the user defined list. User need to mention
the number of test cases to ask how
many list you will enter. If the test case is four, the program should
ask the user to enter four list. How to achieve that? We already have met the
friend who can help us to do that for loop with
the test as range. But hey, why are you using underscore as the variable
for the iteration? Are you so much lazy to find at least one letter to
define the identifier? It's usually done when the
variable of the iteration is used only for keeping
the count and there is no other
significance in the program. That is, its value is not
used inside the loop. This movie is very small. We have come to the climax. User defined list. Get the list from the user as
input. Is it feeling scary? I can understand, but
it is very simple. See how it works from inside. Input statement, as usual, read the input from the user. You know it already that input
read all entry as string. User enters the list of numbers separated by space or
any other delimiter. Input treat the space separated values that
user enter as one string. Do you remember the old friend split from string operations? Input string is separated into individual values
using the split. Map function make
all the element into integer and feed the values
to the list function. The space separated
integer values are mapped into the
format of list. Important thing is user need to enter the values
separated by space. Any other delimeter like
Coma is to be used, mention it as per the rules of split that you have
learned in string. I give it as homework for you. Then calculate the average
of values entered using the function recipe that
we have already defined. Program is ready to serve. I'm testing the code
for the four use cases. Python will not leave me
till I enter four list. Be very careful in
entering the test cases. If you provide 100 test
cases, God bless you. Number of elements in each
list is user's freedom. I will be providing
five values each. It returned the average and
asked me for another list. Once I enter four
list as use cases, program has stopped
asking me the values, allowing me to take the break. This time, I will
take a quick break and join you in the next lesson. In the next session,
we shall see someone who looks similar
to the list Tapal. We shall meet Tuple learn it similarities and difference with the list in the next session.
31. Tuple: I Tapal is the brother of
list who is bit strict. Tapal is a sequence
of elements that are very much similar
to its sibling list, but Tapal is immutable. They cannot be modified and
their positions are stable. Once the list bag is packed, anyone can add or remove
the things from the bag. But when the tuple
bag is packed, no one can modify the
packing, it's sealed. Even the creator, I mean, programmer who defined the tuple has no authority
to modify a tuple. Only thing he can do is he can replace the old
tupel with a new one. List and Tapal look similar, how tuple is differentiated
from the list. The visual difference
between list and Tapal is tuple is packed
inside the parenthesis, unlike list, which
is inside bracket. But functionally, there
is much more to it. Take an example. Name of a person is to be stored
in the form of first name, middle name, and last name. Their order must remain
same to make better sense. If it is stored in the list, someone who has just
learned the program and in experiment phase may sort
the element alphabetically, which might make the data
useless or meaningless. We cannot add, remove or even reorder the
elements in the tuple. If reordering the element will alter the
purpose of sequence, tuple is preferred over last. You have unknowingly
encountered the tuple before. In function module,
we have developed some functions that
return multiple outputs. The output of the function is collection of the elements
in the form of tuples. For example, this
area and perimeter of a rectangle function has two
output area and perimeter. Just assign them to a variable. You got a tuple of elements. I'm providing a
variable tuple two and assign the output of the
function with some input value. Print the tuple two and you will discover the data
in the form of tuple. If you want to confirm, check the data type
of the variable. If the elements in the tuple are sad that they need to
be recognized with the help of the tuple and they do not have any
individual identity, it is possible to give separate name for the
element in the tuple. If you have individual name
to the elements of the tuple, you can assign them if you need to recognize
them separately. The element have got individual
name and they are happy. Tuples can be used along
with and inside the list. Here is the list of tuples with name and age of few
uncles and aunties. I have a disclaimer like ATVsu. I don't have any idea about your family members or friends
who have same name or age. These are random
names I have taken. If you found any similarities, it is just coincidence.
I hope it is clear. You can access the details
of tupels using for loop. Each loop has two elements, name and H, hence
taking same variables. For name comma H in list
of uncles and aunties, I want to print the
statement in the format of particular person is so and so year old,
execute the code. Just like the list
comprehension, there is tuple
comprehension also. Syntax method,
everything remains same. Here are a few examples
of tuple comprehension. Not explaining what are
the elements of each of these tuples as you have
become an expert now. You need to tell the
Python that this is a tuple and use parenthesis. The content inside is
same as that of list. Print both the tuples
you just created. Hope you are now very clear with the difference and application
of list and tuple. We shall see one more data structure dictionary
in the next session.
32. Dictionary: A We know that list is the collection of
unmarried elements. When each of the elements
in the list has a partner, it will become the
collection of couples, which is called dictionaries. But why the elements
demand for a pair? Why can't they be single? Consider this example. In the school where you study or the organization
where you work. There may be multiple persons with the same name as yours. Your name and surname are
not your copyright, right? Consider in the broader terms like in state or in the country. Name cannot be used as
the reference to get the information about any
person in the database. So what could be the
unique identification that defines only you? People have unique code like
roll number or employment ID or citizen ID that differentiate
the person from others. The unique element
that differentiates the data from others are
called key or index. Let's come back to our mapping
data type, the dictionary. Dictionary is the
cousin of list, like list in many aspects, but one major difference. In list, we define the elements with the
help of its position. If you did not understand, we will map the element with the help of index
of that element. But in dictionary, value is
defined with the help of key. I know these words
sound very terrible, but what they mean is simple. Just consider the
dictionary that we use to find the
meaning of any word. It has collection of
thousands of words. How you refer to any
data in dictionary, dictionary data
consist of pairs of words and its synonyms
or definitions. You search for the
particular word, which is the keyword to get the meaning,
which is the value. Similarly, dictionary
is the collection of key and value pair. Let's take the same
previous example of role number and names. Being a lazy man, it is difficult to
find new names, so I will fetch the name I have used in the
previous session. Now uncles and
aunties has become college going kids
and has role number. Here names are
recognized with the help of unique key, that
is role number. Keys cannot have duplicate,
but values can be. We define the value
with the help of key unlike list in which
element is defined by index. You can even use function get like list,
dictionaries are mutable. You can add, modify or delete the elements
in the dictionary. Say students are exchanged
between the university. Now Smith is replaced with Mike for the row
number one not three. Update the role
number one or three with Mike. Now print people. If you feel lazy
to write update, just as a new value
to that keyword, your work is done. Dictionary name dot keys
as well as dot values, as their names suggest, return only keys and
values of that dictionary. For the dictionary,
people, people dot keys, return all the keys
in the dictionary, and similarly People dot values return all the name
of the people. Dictionary is open for all. Adding new member to
the dictionary is easier than adding jam or bread. Assign the new value to
the new key, you are done. Being the brother of list, mutating the dictionary is more or similar to that of list. Like list, you can remove
or pop the elements. Consider one more different
example of using dictionary. Here I am defining the
properties of the car. Using this way, dictionary can be used to store
the information, access the data, and
add more information. Genius Iu might have observed
one thing in dictionary. Syntax for assigning
the values to the key or for learn
one get on free. Same method is used to adding new member to the new key and also updating or replacing the old values with a
new to the existing key. Syntax remains same. Just include key in square bracket and assign
the element. That's it. Same method can be used to
alter the elements too, just as a new value
to the existing key. It will replace the old
element with a new one. Most list operations
hold good for the dictionary like adding
two dictionary and pop. But instead of index, you ski. That's the only
thing you need to remember while dealing
with the dictionaries. I don't want to make you sleep. Try to practice the
dictionary concepts well and we shall meet
in the next module.
33. Introduction to Libraries: What is a library? This is not English class. We have nothing to do
with its definition, so let us not worry about it. What comes to our mind
when we say library? As per our understanding, library is the collection of useful resources like books or articles that are
stored in one place so that we can access any
resources when we need. Similarly, in programming,
we use the treasure full of pre coded resources to make our
programming task easy, which is called libraries. It's just like when it is
difficult to prepare pizza, order plain pizza from the nearest seller and customize
as per your requirement. As we discussed
in the beginning, one of the reasons behind the Python popularity is the number of
libraries it offers. We can count the muscles
or nerves in our body, but we do not have the count
of libraries in Python as they are increasing
day by day. But wait. Now you have become the
expert in programming. Then why you need libraries? It is very important to learn
the libraries because we do not use the programs just for computing
basic calculations, but to solve the complex
task like developing software or programming
difficult problems of science and engineering, for example, machine learning. Technical problems
like these are difficult to program
if not impossible. It is necessary to write heavy program even for minor
details of the problem, but are we the only person who work on that
category of problem? Definitely not. We are not the first person and
not even the last one. Problem statement
might be different, but similar algorithms
were used by many people. Hence the commonly
used algorithms were pre coded and stored in
the form of library. We can use the resources from the library to
complete our task. In this module, we talk about the unsung heroes of
programming, the libraries, like the backstage crew, who might not be visible
for the audience, but without their effort, end result might
not remain same. I have already given a lot of
buildup for the libraries. Now we'll introduce
a few of them. Here is a list of popular
Python libraries. You can pause and look
as I cannot stand here. As we cannot discuss all
of these libraries here, let us explore two popular and commonly used
Python libraries. Math and Numpi
library as example. Are you excited? Give me thumbs up and join
the next session.
34. Math Library: In this session, we
explore the math library. The name of this library reduced my effort of
defining the library. It does what it says. In simplest term, it is
the mathematical library. To use the library in US system, it is necessary to
have them installed. To install any
library, type PIP, pip install library name, here I mentioned
math in the console. Wait for the packages
to get installed. Installation is done. Library is ready to serve
your programming need. Let us start with simple use
of math library as you are a beginner and I cannot make you to learn to drive
the truck directly. Let us start with a bicycle
using the math constants. Bicycle has two wheels which
are circular in shape. Let us go back to the problem of calculating the
area of the circle. For calculating the area, we use 3.14 as the value of Pi. Anybody here, genius enough to define the value
of Pi precisely? Even if you know the
most precise value, do you have that
much time to write the decimal values?
I don't think so. Why we even worry about it when the math
library can help us? Math library define the value of Pi to the best
possible precision. First step, we need to call
the Math Library for help. Ladies and gentlemen, please welcome the math
library to the work. No, math library will not
appear if we call like this. This is not the way to
call the library to bring the math library for
action, write import math. This will get the math to work. Now math library is
ready to help us. Now I replace the
value of Pi with math, the library name, which alert the math that
we need some help. Then dot Pi, which inform math that we need the
value of Pi here. We can see the value of
Pi is defined by math. This will work fine, but calling the whole
library just for one or two function
is like calling the whole army to
fight with one person. In such case, call the math
to give us access only to Pi. From math, import Pi. If you need more than one, but still very few functions, import them using comma, like in this example. Remember, sine take the argument
in radiance, not degree. Hence, if you have angle in degree for the
technometric problems, convert them to radiance first before you feed
them to the calculations. If you have more functions, then it is better to call
the whole math library. Are you facing difficulty to convert them from
degree to radiance? Why you worry about conversion when we have the math library? You can convert the
angle in degree to radiance by using function
math dot radiance. To get the angle back
from radiance to degree, we have the function
math dot degrees. Along with Pi, math defines a few other mathematical
constants like E and tau. Math will bring mathematics
to your programming. Now let us move to trignometry. I know some of you might
have started feeling sleepy hearing the
name, but don't worry. I'm not your math teacher. I assume you have attended
your math less promptly, and you know sine, cosine, and tangent well. We just see how to use
them in math library. First, sine function. I do not measure the sin, but measure the
sine of the angle. Angle we have assumed is
Pi divided by 4 radians, which is 45 degree. Similarly, math
dot cos function, measure the cosine and math dot ten return tangent of the angle. Everything here is
easily understandable. Just add A in front of them. I mean, A sine A
cause and a ten, they get converted
to inverse sine cause ten respectively. Add H at the end
of them, sine h, cse H, and tan H, they
become hyperbolic. So easy to use math
library, right? Now comes exponential and logarithmic functions
to the math party. EXP, which stands
for exponential of X is constant E rises
to the power of X. In the current example, E is rise to the power of six, which is approximately
four not three. Next function is log. Log need two assistance in the form of arguments,
value and base. First example, logarithm
of 81 base three. This gives riddle to the math, three to the power of
what is equal to 81. According to Python
math, it is four. If you have any objection, clear it with Python. Pow is power with two arguments. Power gives the power to rise
the value exponentially. Power of X comma Y indicate
X rise it to the power of Y. In this example, six is raise
it to the power of four. SQRT stands for square root, square root of 625 and 156.25. Now let us see a few
numeric operations of math. Here you see permutation
and combination of N and K in the form of N permutation
K and N combination K, where K is less than or equal to N. Otherwise, you get error. See another popular
math function, GCD, not the brother of LCD. It means greatest common
divisor of two integers. The room you are sitting
now has ceiling and floor. Ceiling is the nearest
upper surface of the room, and floor is the lower
surface of the room. I'm not interior
designer of your room. I'm talking about
them because math offers SL and floor to
the numeric values. Math dot C is nearest higher
integer of the argument X, and floor is nearest smaller
integer of argument X. There are other
functions like Fabs, where F keeps the value float
and ABS is the nickname of absolute the function factorial
explains its purpose. There are more
things math can do, but I don't want to make your
head a room of confusion. These functions are
most widely used, and if you want to dig more, ask anytime anywhere teacher, Google or refer the
math documentation. It offers detailed
information on the math library or any
library for that matter. Search for math documentation in Google. You will find it. Now we shall explore one
more popular library, NumPi but after a small break.
35. Numpy Library: Okay, everyone,
please gather around. We are now going to learn
about one more Python library, Num Pi, which is a nickname
for numerical Python. Get ready for the
adventure with Numbi. But who is this Numbi? We need some introduction
of our chief guest. NumPi deals with
multidimensional array and matrix data structure. When you think of scientific
and engineering problems, then think of Numpi. Numpi allows a lot
of operations. It's fast and efficient. Numpi would be something
you cannot afford to miss if you are a data science or machine learning enthusiast. To install Numpi as usual, the same statement
PIP install Numpi or Conda install NumPi if
you're using anaconda. I have already installed
Numpi Hence in sweet words, it's telling what
happened to you? The package is
already installed. Once you install, call
it for work using the statement import Numpi and ask its portion with itself. Use to underscore on
both side of version. Already in math library, you might have observed that when we work with the library, we need to call its name frequently to use
their functions. It is difficult to call it again and again
with its full name, as we humans are very lazy. NumPi is already the short
form of numerical Python and we keep short name to
a short name numpi say NP, which is very popular
nickname to it. Okay, lazy guys. Now
let us create an array. I call NP for help and say, I need to create an array
and enter the elements. Creating array with the
NumPi is so simple. Even the list can be
converted into array. Here, the list is defined and same elements are
provided to array. Why we do that when we can
keep it in the list format? Because NumPi array is very strong and
powerful than the list. It can handle heavy lifting and accommodate complex
matrix operations that list cannot
even imagine and make R if you ask
the list to do so. Rnm dot D type will return the data types of the
elements in the array. If you need to alter the
datatype of the elements, add the statement of
T type and define the required datatype while defining the array
in this format. The number 64 indicates the
number of bits per element. This is commonly
used in C or Fotron. For most cases, use end 32 and float 64 for good
accuracy and speed. Tell you the numpi
is multidimensional. If you said no, then you must be feeling sleepy.
Please wake up. Here is an example of
two dimensional array. Two dimensional array is a matrix that we
use in mathematics. Array shape will return
the size of the array. It means two rows four columns. Np zeros will create
the array of zeros. Zeros with just one argument
make one dimensional array. In this case of five zeros. Similarly, two
dimensional zero array with rows and columns
can also be defined. One step ahead of this is the example of three
dimensional array. Here is how it looks. Like us, NumPi cannot go
beyond the third dimension. In a similar way, we can
create the matrix of ones, which is filled
with the value one, and I for identity matrix. But identity matrix take
one argument because it is symmetric and must have same
number of rows and columns. In other words, identity
matrix is a square matrix. I assume you have went
to your math class in high school promptly and learned the matrix
operation well, as I cannot teach you
the mathematics now. We just look at how to perform
the operations in Numbi. Array dot T is the transpose
of the matrix which does magic and convert the rows into the columns and
columns into rows. I will create one more
matrix for the operations, array seven, which is also
two cross four matrix. Now I'm adding array
five and array seven. Adding two or more matrix is
as easy as adding numbers. Only condition for the
addition and subtraction of two matrix is that the size
of the matrix must be same. Otherwise, you don't get the
output but error instead. Multiplying the matrix
with a constant will multiply the value to each
element of the matrix. In Num Pi, finding the inverse
exponentials and root of the matrix are very
similar to how we do that to a constant value. Now look at the
operation that broke your head during your schools
matrix multiplication. Very simple, but the
number of columns in the first matrix must be same as the number of rows
in the second matrix. It is not the rule of num Pi, but the rule of mathematics. Your headache is solved
in a matter of seconds. Now create the array based
on arranging the values. The function arrange
is the brother of range that we use in four loops. It works same as range, first value, last
value, and step size. But what it does is it creates
one dimensional array. If you want to convert
any one dimensional array into two dimensional array, use the method reshape. Reshape will break
the long chain and provide new
shape to the array. Now let's meet our
old friend slicing. Slicing one d array is exactly same as we
slice in the list. Here, let us go
one step forward. Two dimensional slicing sounds complicated, but it is not. It is as easy as one
dimensional slicing. Here we treat the row number
and column number as index, but start the count from zero. Two dimensional slicing will return the sub matrix
from the matrix. Here is the example of how
the two D slicing works. Consider only row first. You know well that
zero colon two is zero and one, one
step less than two. I have selected zero
through two first row. Now consider column. As per the index for
one column four, select column one,
two, and three. Now the coinciding matrix
is our required result. Is it really difficult?
I don't think so. When we need to practice
the concept of programming, but we don't have the real data, what we should do?
What is there to do? Create random dummidata
to work with. What if I tell you, Numpi
can do even that for you? You can create the
random array by defining the size of the array and
range of values you need. I will create the random list of integers using
random dot Randent. Random is the function in Numpi and randint is sub
function in random, which written only integers. Are you okay with anything
from zero to infinity? No, then provide input range, S numbers within 50. Followed by the
size of the array, I need five cross five matrix. I will create a three
by five matrix of fractions using random dot
rand with size of the matrix. Great. Now I strictly
say the Python, choose the values only
among the provided list, which has five elements. Obviously, method
name is choice. The rest of the process
remains the same, give the size of the matrix, for example, three cross three. Now let us extract
the value from the array based on
some conditions. First, I will create the random
array of integers within ten and size 12 and assign
them to a variable named data. Now extract the values based on some conditions like elements
greater than three in data. Extract the numbers
that are divisible by two or simply even numbers. Great. Now we shall
explore one more method, empty array, but it looks like the zero array.
What's the difference? Difference is elements here are uninitialized that cannot
be used for any operations, but you can add
the elements using other methods like
using four loop. Enjoy the libraries. Math and Numbi are popularly
used library of Python, hence we have selected them. But Python supports thousands of libraries serving different
purpose problems and fields. We shall end the module now. You can learn the
other libraries as per your requirement. We shall meet in
the next module.
36. Pandas: Hey, there. Before exploring machine learning algorithms
and data science projects, it is important to learn a few libraries that are very much needed
for programming. As part of that, we shall
learn about Pandas today. Yes, I know what
you are thinking. Pandas. Are we here to
watch cute Panda videos? I wish, but Today we are talking about the
Pandas library in Python, and trust me, it is
equally adorable, but in a programming way. For anyone dealing
with the data, Pandas library is as
lovely as the animal. Let's start Pandas
with a little story. Imagine you are in
a massive never ending supermarket
called Data Mart. All around you, there are
rows and rows of data. You witness huge amounts of data everywhere around
you, mostly unorganized. You are there standing clueless, holding a tiny shopping
basket, wondering, how on earth do I find
what I need in this mess? Well, my friends, that is where our superhero comes in Pandas. He helped you find what you need among the infinite rows of data. So Pandas is a powerful data analysis
and manipulation tools. For Python, that will help
you find, clean, organize, and manipulate the data like a P. You could say Pandas
is like that one friend who cleans up your room
and then help you find your lost things if your lost
items were actually a data. Okay, forget that.
Here is the real deal. Pandas gives you
two magic tools, series and data frame. Think of series as a single
column like a shopping list, and data frame is the
entire grocery cart, a table that can hold
multiple columns of data. So basically, a
series is a column, and a data frame is a
collection of those columns. Want to slice and dice
your data like a chef. Pandas has you covered. Need to find all
the people named John who bought
bananas on a Tuesday. Pandas can do that, and it won't ask why
you need to know. Imagine asking your friend, Hey, can you find all the
people named John who bought bananas on a Tuesday? They would probably look at you like you have
lost your mind. But Pandas Pandas
will do it without judgment because it's a library and libraries are
cool like that. Now let's create a series
and data frame because talking theory is like watching a cooking show and
never tasting the food. I'm not here for that
kind of torture. Here is how we do it in Python. Folks first import pandas, import pandas as PD. Pandas, of course, is too
cool to use its full name. So we just call it PD
like we're best buddies. Let me create a series of
number of fruits at a store. Number of fruits is
equal to PD dot. We are calling our best per D pandas and ask for a series. 152230 are number of
different fruits. Print number of fruits. We have defined a series. You can observe one more column
appeared with 01 and two. This is the index,
unique reference for each of the values in a
series or in the data frame, just like we had index
in the string or list. The index in a Panda
series is like a name tag. It tells each value who it is. You can even rename them. Let us make changes
while defining itself. A index is equal
to list of apple, banana, and cherry.
Printing it again. Now our series has become
something meaningful. Want to have more
fun, I will rename the existing index
with a new list of index using number of fruits, our series name dot index
is list of fruit images. If you're using Windows, use Windows key plus
semicolon and in Mac, use Control plus Command plus space to open Images picker. I will add images of
different fruits. Print series again. Now your series is
fruity and fun. Now let's create a data frame. Name of data frame is DF,
name whatever you want. Dataframe must have
multiple columns and each column must
have a column name. Our data frame has
three columns, name, age, and favorite food. Each column has
four rows of data. Names we have are John, Jane, Jake, and Jill. All have names starting with J. What a coincidence. Data we have in age and favorite food, are these people's age and food they like
respectively in the order. Let us print this data frame so that you get a better idea. We have got ourselves
a data frame. John is 28-years-old and
like pizza and so on. Information is printed
in the tabular form. Okay, now that we have cocoed
up this tasty data frame, let us learn how to slice and dice it like a
professional chef. But no crying over like
slicing on in here, only joy from data slicing. Want to grab a specific column, es DF with only name, and we get a series of names, just like you had to call
out role in a classroom. In the real world,
data isn't as tiny and neat as four rows of
hand typed information. It's a wild jungle of thousands and sometimes
millions of rows. Imagine sitting down
to manually type every sales transactions,
every customer details, and every inventory update, your keyboard would probably pack its bag and live forever. Thankfully companies
are smarter than that. They maintain all this data
in handy spreadsheets, Excel files or CSVs. It is like having a treasure
full of information, neatly organized
and ready to use. Instead of wasting time manually creating
the data frames, we just import the file
in Pandas and boom, your data frame is
ready in seconds, let the spreadsheets
do the heavy lifting while you focus on
digging into the insides. So now we read CSV
file with Pandas. I'm using employee salary data. It is a Dummi data
with 50 data points. Import the data using pd dot, Read CSV, and then
path to the file. You need to specify
the location and directory where the
data is stored. I have stored the data
in the homepage of Jupiter and hence
import it directly. Just like that, we have got a data frame without the hassle of defining
all those loads of data, and now you are ready to slice and dice your data
however you like. If you want to look
first, few rows of the data frame, check dfdt head. You get first five
rows of the data, and if you want to
see more than five data points, just mention it. Python is very friendly. It returns whatever you ask for. Now some of you
might be wondering, why should I use
Pandas when I have got my trusty Excel to
do all these jobs? Pandas can handle data so
large that makes Excel wet. It is fast, it is flexible,
and it can merge, filter, and group your data
like it's a magic went. Excel is like a bicycle
with training wheels, while Pandas is rocket ship that can take you
to the data moon. No, I'm not exaggerating much. Next up, let's talk
about set index. We had the employee data. They have unique
reference, employee ID. Instead of recognized
by the index like 012, they deserve to be recognized by their employee ID
because it is unique. Right now, our data frame
rows are indexed by these boring default numbers,
but we can change that. Let's make it more personal
using set index to set a more meaningful index
like their employee ID. DF is equal to df dot
set index employee ID. No more generic numbers. Now you can refer the data
by the person's ID directly. We have data frame now. We need to extract the
information from the data frames. We have two data
ninjas for doing that. Lock and iloc. These are your go to weapons for grabbing specific
rows and columns. But let me tell you, they have very different
personalities. IloC is index based and
lock is label based. Iloc is I don't
care about names. Just give me the numbers guy, and that's the difference
between lock and iloc. Labels versus positions. Both ninjas, both awesome. I will tell you one fun fact. Even the experienced data
professionals sometimes get confused which one to
use. That is very normal. Let us see some operations, then you will understand better. Starting with iloc, ILC
doesn't care about names. No, this guy is all
about positions. You ask for information
in any rows or column, and he does it without
asking questions. IoC reads row first
followed by column. Now let's say you're
interested in a single row, like you are gossiping about only one
person in the group. You can use ILC to
get that gossip. I stands for index and
lock for location. Want to know about the
person sitting in row one, that's how you get them. IC one, return the data in the index one, gossip successfully. But remember, iloc is
all about position. Like in sequenced data types, colon is used to
mention the range. This line is telling to return
all rows and column one. Column one is not first column because we have zeroth column. I hope you remember Python had a bad math teacher who
taught counting from zero. Here is the output. You can display the range
of rows and columns. I lock with colon
three comma zero, return rows zero, one, two, and column zero. Next, we have Lock. This guy is all about labels. He says, give me a name and I
will find the data for you. He's precise, focused, and doesn't care
about the position. You can use him to grab the specific rows and
columns by their labels. I want to know the name
of the person having employee ID e003. Only name. Let me ask dataframe dot
log row e003, column name. Okay, I don't get any other information
just with the name. Who stopped us from
getting more information? Just write df dot log
e003. There we have it. That employees entire
life story right there. Let us give some twist. Get data based on some
conditions, dataframe dot log, find data of all person having their salary greater than
or equal to 3,000 units. We are interested in
only those who make good money. These
are those people. I'm also concerned about
their departments. I want to find those
people having salary 3,000 units and belong
to IT department only. These are our short list. In any datasets, there are good amount of junks along
with the information. Lock help us in
filtering the data and servers that only we are
interested in. Thanks, Log. Now let's move to
some fun methods. First up, the describe method, the data analyst
version of reading someone's entire life
story, but less dramatic. So df dot describe Describe gives you all the juicy
statistics about the data frame. It is like data's
resume, the mean, the minimum, the maximum, everything you need
to make judgments. Now let's calculate something
simple like the mean edge. I mean, why not? Df h dot mean. That returns average age
of our data friends. That means
statistically speaking, our group is pretty
young and energetic. Let's talk about uniqueness. The unique function
will tell you all the distinct
values in a column, like pointing out all the unique personalities at a party. If you check for unique
values in department, you get list of the
departments used in the data. All data belong to one
among these categories. Let us filter some data now, like you're filtering
your Instagram feed to see only what you
really care about. This works same as
the lock method. For the previous data frame, suppose we want to find all the people whose
favorite food is pizza. Easy. DF having DF or favorite
food is equal to pizza. Now let's talk about merge. This method is like a
matchmaker at a party. Its job is to bring
different datasets together like finding
two long lost friends. Suppose you have
two data frames, one with names and ages and another with
names and cities. If you see names, they are same. That means there are two data frames belong to same people. Naturally you want
to combine them. Who is ready to manage two datasets belong
to the same people. That is where merge
steps into the play. Create a new data frame, merged df is equal
to pd dot merge, DF one and DF two. Based on what should I merge? We need to merge on comparing names because names are same. That displays the
merged DF like that, the names, ages
and cities are all living happily ever
after in one data frame. Merge is the master
of matchmaking, bringing data together
on common ground. In this case, the name column. Next we have join. Now join is like merge, but it works more like
neighbors sharing offense. It joins two data frames side by side based on their index. Suppose we have set the index of both data frames to name. Now join them based on name. Join df is equal to DF
one dot join df two. See, neighbors
living side by side, sharing all their secrets in
one nice joint dataframe. Now let's say you have got two datasets and you want
to stack them together. Either one on the top of
the other or side by side, like building a data sandwich. Enter Concat. Here is how you can
stack two data frames on top of each other like
you're piling up pancakes, pd dot Concat df df two. But if you prefer
side by side actions, just change the axis, pd dot Concat df df two. Acess is equal to one. Concat lets you build your data skyscraper
anyway you like. Now let's check the type of
data in your data frame. This is asking, what are we
really dealing with here? Is the He column
full of integers? Is the city column
full of strings? Let's find out df D types. We have got integers
for H and subjects, a fancy word for text for city. Now we know exactly what kind of data we are working with. Now, let's say you want
to change someone. I mean, change the
type of a column. Maybe you have decided that the He column should be a
float instead of an integer. Es PC, and done using astype. Tfh is equal to
dfht astype float. He is now a float like a number that's ready
for some serious math. If your data ever
needs a makeover, astype is your tool. And that my friends is
your Pandas tool kit. You have got set index to
personalize your data, lock and ei lock to
grab specific slices, merge and join to bring
datasets together, and concat to stack them
like data sandwiches. Now go out there and make
some data magic happen. And remember, when you handle
tabular data in Python, Pandas is something
you cannot miss. Now you must be feeling
Pandas as cute as Panda, the animal or horrible
like angry Panda. With practice, even angry panda, turn out to be cute one, see you in the next class.
37. Matplotlib: Hello future data artist. I will tell you one hard fact. Most of us are
allergic to numbers. Working with huge
numeric dataset is the best way to fall
asleep in minutes, even better than sleeping pills. Today we are learning
visualization and with visualization, we are turning the
boring numbers into colorful stories.
Yes, that's right. We're about to
become data artist. Welcome to the world
of Matplotlib, the library that lets you create beautiful graphs and
chart from your data. Because numbers
without visuals are like pizza without
toppings, boring. First thing first, what
exactly is Matplotlib? It is your personal canvas
for drawing charts, graphs and plots from your data. Imagine your data
as a giant pizza. You have got all toppings, but matplotlib is what
lets you slice it, present it, and make it
look delicious. All right. Step one, importing
Matplotlib, setting the stage. Let's go to the code. First, you will need
to import Matplotlib. Instead of typing out
Matplotlib every time, it's your full legal name, we call it PLT because
we are cool like that. Import matplotlib
dot Piplot as PLT. Now we are ready to roll. Let's start simple like a baby's first step,
but without filing. Suppose you want to plot how much coffee you
drink every day. So days is equal to
Monday to Friday. We are considering only weekday because on weekends we
don't drink coffee, we drink something else. Coffee cups is equal
to two, three, one, four and two. PLT dot plot. Das coffee cups, plt dot
show to display the plot. Here is your first plot. What does it show that you have an inconsistent caffein habit and should probably see
a doctor by Thursday? Now this plot is nice, but it feels a bit nameless. Let's give it some labels and a title so people know
what they're looking at. Because without a title, it is just a bunch
of random lines. First, let's name Xs, plt dot X label,
days of the week. Now YXsPLt dot Y
label, cups of coffee. Finally, a good
title to the plot. Plt dot title,
caffeine consumption, now plt dot SO much better. Now we know this
is a story about your caffeinated journey
through the week. Now let's add some
color and style. Sure the plot works, but it's plain like a toast without butter.
Let's spice it up. You can change the line color
and style to make it more visually appealing or just
to flex your artistic flare. PLT dot plot, Ds
oma coffee cups, color equal to red, line style equal to dotted, and marker is equal to O. I will keep other
things unchanged. See what happened now. Can you spot changes?
Check it out. Now we have got style, red line, dashed pattern, and
circles on each point. Like we're throwing
a disco party for your coffee addiction. Let's take things
up a notch with a bar chart because sometimes line charts
are like spaghetti, too wingly bars they're solid, confident, and stand tall. Here is how you create bar chart showing how much pizza
you have eaten this week. Days remain same
Monday to Friday. Pizza slices is equal to four, three, five, two and four. Plt dot bar Des pizza slices, and I will label X
label as days of the week and Y label
as pizza slices, plt dot title, weekly Pizza
consumption, finally plt.co. Boom. Solid bars representing
your pizza consumption. Not only do you love pizza, but now the world knows about it in glorious bar chart form. And remember, no one is judging your wetness
taste binge eating. Next up, we have got pie charts. They're great when
you want to divide things into neat little slices. Plus you can always
pretend it's actual pie. Let's say you want to visualize the different type of foods
you have eaten this week. So foods equal to pizza, burger, sushi, and pasta. Amounts is equal to 35, 25, 15 and 25. PLT Pie amounts, ma
labels is equal to foods. Autopicity is equal to
one decimal points. PLT title, food
breakdown for the week PLT dot SHOW and there
it is a pie chart. Look at all those
delicious slices. You have got 35% pizza, 25% burgers, and probably too little
sushi for your own good. Just like a real pie, this one makes you
hungry, isn't it? Subplots, multitasking
like appro. Now, what if you want to show multiple plots
at the same time, subplots to the rescue. Think of them as
the Netflix screen with all the different shows. Only instead of binge watching, you are binge plotting. Let's make a subplot with a line chart and a bar
chart side by side. First subplot, PLT dot
subplot, 12 comma one. This means layout has one row, two columns, and
this is first plot. PLT dot plot, Des coffee cups, PLT dot title, cups of coffee. Now second subplot,
PLT dot subplot, one comma two comma two. This tells second plot. This time we have bar, plt dot bar, Das
coma pizza slices, plt dot title, pizza slices, plt dot tteyout plt dot sh. Now you can look at your coffee and pizza habits simultaneously. It is like multitasking
for your data brain. Plus, it is a reminder that your food choices are just as important as your
caffeine addiction. Egends the side kicks
of every hero plot. Think of legends as
information board. We shall have the plot
of coffee cups and pizza slices in same
plot PLT dot plot. Das coffee cups, label is
equal to coffee, PLT dot plot. Das pizza slices, label
is equal to pizza. Plt dot X label, days of the week, plt dot label, quantity, plt dot title, Coffee versus Pizza consumption. Now you need a legend to
tell people what is what, or else it's just a bunch
of confusing lines, plt legend and PLT dot Show. Now we have got both coffee
and pizza consumption in the same plot with a legend. It's like an epic battle
Coffee versus Pizza. Who will win? My
money is on pizza. What about yours?
Customizing the plot, adding grids and tweaks. Feeling fancy, let's add a grid. It's like putting
lines on the map. It helps you navigate
through your data. I will add one more line
before PLT show plt dot GRID. True. Now it is like
playing battleship, but with your coffee
and pizza data. It makes everything look more organized and let's be real, a bit more professional, saving your plot for
future reference. Finally, you have made an amazing plot and
want to save it. Maybe to print it out, hang it on your wall, or show off to your
data scientist friend. Easy plt dot Save fIC and your
image name myplot dot png. Now your plot is
saved as an image forever immortalized
in your data journey. Frame it, gift it, or just tear at it proudly. That, my friends, is
matplotlib in its glory. You have learned how to create
line plots, bar charts, pie charts, subplots, and even how to save your creations
for future generations. You're officially
a data artist now. Go forth, create beautiful
visuals. Happy plotting.
38. Introduction to OOP: Welcome to the first lesson on the last module of the course. The concepts you have
learned till now are like your well known
friends and relatives. You know them already
and meet them regularly. Operators, logic conditions
like and or not, decision based on comparison, loop like routine works, collection of data, everything you use in your day to day life, even before knowing
what is a program, and you might not use
those fancy terms. We have just introduced
their programming versions. You have learned how to use the same things in your program. Those concepts
made Python a good scripting or functional
programming language. I know you hit that difficult
to digest big words, but their meanings are not as
complicated as they sound. It means programs were mainly based on logic and some action. Let's go through
another unseen phase of Python as object oriented
programming language. I know this term create
panic among the listeners, so let's call it OOP. If you're very courageous, go to any search engine
and find what is OOP. You will feel it like the
plot of horror movie. In fact, there is no such
complexity in this concept. Even OP is something
you know already. But the problem is the
complex and scary definitions make it feel like OP is
brought to Earth by aliens. The fact is you have met them
without knowing about them. Hence Pi may seem a bit confusing at the beginning,
but don't worry. I will try my best to keep
things as simple as possible. That's my promise, and you must keep your promise to practice
as much as possible. This model might be a bit
lengthy compared to others, but we shall have more
fun in this module. Show me some enthusiasm, guys. You are learning something new and learning should
always be exciting. Forget about programming now. What do you understand by
the term object oriented? We are trained to find complex things even
in simple words, don't use much brain, only use fraction of them. At least you will
understand that this is something
based on objects. When you started
learning English, I think object is one of the word you have learned
within a few days. You know this word very well so that you can explain
better than me. Then what is an object? I don't want definition, even I'm scared of it. Just by using ordinary
common sense, can I say everything your wide open eyes can see when you look
around are objects. As you're watching this video, there must be digital gadget, maybe a laptop or
smartphone or a tab. That gadget might be
resting on a table. I can see a lot of objects
messed around my table. That is one of the indication
that I am an engineer. That table, laptop, WiFi router, pen, paper, thousands of
wires running long and wide, spiller food, sleeping
kitty, everything, whether you kept organized
or messy, are objects. This is just about the table. What if you look
around the room? No, we don't have that much
time to list everything. Let's stop it if you have
understood what is an object. If object is so
simple to understand, then how it is possible that object oriented
programming is complex. OP is a programming concept that allows us to define the real world objects
and their properties. If you understand, then great. No doubt you are
very intelligent. If you don't, you will
understand as we proceed. OP is the hidden
talent of Python, but it is very important to learn to be a good
Python programmer. As a programmer, you get
a lot of powers with OB. Keep your first step
ahead towards Op. To understand OP, it is important
to know the terms user. Imagine entering kitchen without knowing the kitchen ingredients. You may end up with good
science experiment rather than dinner and God bless those
who are supposed to eat it. Let us understand OP
terms with an example. Do you like fruits?
Don't worry much guys. Even if you like it or not, I don't make you to eat. If you're feeling hungry,
I'm extremely sorry. You can pause, get something
to eat, and then continue. Fruit is the real world object. We need to define the
fruits in the program. Assume I'm computer and someone explain me how
a fruit look like, and you don't need to explain
me in Python language. You can use the language
you understand, and of course, the language
even I understand. Is there anyone who can
answer this question? This question is
very general and someone may ask which fruit
you are talking about. If someone ask how
to recognize mango, I can answer yellow color, yellow pulp, one seed
inside, sweet taste. What should I answer for? How to recognize fruit? Do I need to say fruit
look like mango, apple orange
pineapple and so on? Where should I stop? The problem is fruit is not a single object, but it is a name for a group of delicious plant made
edible objects. When I said fruits, there are hundreds of
fruits available. VOP term, fruit is a class. Group of objects are called class and members belong
to this class like apple, orange, mango, banana,
or whatever it may be, are all called instances. In VOP, we define these instances and
how to recognize them. Our aim is not to send the computer to market
to get some fruits, but to store the
information on how to recognize and
differentiate each fruit. How to define each
instance of fruit class. Distinct property of each
fruit comes for our help. Each instance of
fruits are identified by set of distinct
properties like color, odor, taste, with seeds or not. If the number of seeds, where to throw those seeds or other properties which help us to recognize among
the list of fruits. These properties which
define and differentiate various instances of a
are called attributes. Attributes help us to recognize the person you are meeting
for the first time. Skin color, hair color, and maybe height can be among
the attributes of a person, but don't define his or her
dress color as attribute. OP is innocent. It may take any input from you, but you don't know diss
color can change tomorrow. Hence, attribute must
be universal property, help to recognize the instance. Now we got an
instance of a fruit, and with the help of attributes, we have recognized
it as an apple. Next question is, what do you want to do
with that instance? That's my personal choice. Depending on the requirement, I may directly eat
it after slicing, or I can extract juice from it. Any operations performed on the instance are called methods. Do you remember
method? Let's discuss about method in detail soon. Are you clear with the
terms class instances, attributes and method? These words may be
new and strange, but their meanings
are very simple. We know these
concepts very well, but you just don't
call them as classes, instances and all. That's it. These terms are very important in every concepts of
Python programming. In fact, we have encountered this term multiple times
while programming. It just worked
like secret agent, hence we could not recognize
it. Now let's recognize. I will define my
as usual string. This is a string and
assign this string to a variable named string.
Don't get confused. When I ask the Python to
print the type of this value, look how the output
is presented. It's not saying
data type string. Instead, it written class Star. You know Sterr. This is how
string is called at its home. Does this keyword
class STR says? It says the value
you're talking about is an instance or member
of the class string. That means class
is not stranger. Class was with us
since datatype module, but he was not communicating
with us. Might be introvert. Similarly, if you ask Python, what type of value is two? Python says he
belongs to class It. Not just string, but all the tring in float
complex list dictionary. What we used to call as datatypes are all
classes and value belongs to these data types are instances of these classes. Type function, which we thought earlier to return
the data type is actually a built
in function that returns which class
any object belongs to. Then what about user
defined function? His function is from Mars or
any other distant planet, then it must be no different. Let's check it, however. Why should we keep doubt on? As you know it very well,
how to define a function, I will define a simple function
without any parameter. Say, define message which prints some message hello world. This is a dish without
any ingredient. Yes, it is possible to define
a dish without ingredient. Not in kitchen, but only
in Python functions. But such function will
always return same output. There is no change in the
life of this function. How boring isn't it?
Okay, let's come back. If we ask which class do
this message belongs to, you will see class function. That confirms function
is not from MRs. It is also a class
and defined functions are the instances of the class. Everything we define while
programming belongs to some class and each class has their own set of
attributes and methods. Dot notations we use on data are the methods we are
operating on the class. That answers the old
question left unanswered. When we use Inumeric
on the integer value, we have encountered the
attribute error with the message int object has
no attribute is numeric. The terms used to be scary
then must made sense now. It was actually saying, I am instance of in class. I don't have any
method called is numeric. I hope it's clear. Now we have understood
each data being instance of a class have
the methods of its own, but we are not the
storage device to remember the methods
of each classes. How good it will be if
you find the list of all the available methods
for any given instance. Python is so sweet
that it understand and provide us what we need
before we ask for it. DIR function with a
instance as argument, return the list of the methods available for given instance. Will use DIR with string, but the problem is output feel like alien language
rather than Python. For a moment, ignore those
sitting inside the underscore. Concentrate on the
other methods. Feels like familiar
faces, isn't it? The ones with the
double underscores on both sides are not
the users use often. They were called
in the back end of the processing to perform
specific operations. For example,
underscore underscore a underscore underscore is called in the back end
when you add two strings. These special methods
are like chefs specialized in particular
dish who work in kitchen. When you order Python to add two string in the service area, Servo transfer the order to
the chef in the kitchen, underscore underscore,
add Underscoe underscore. You don't get to see
the work of chef, but the final output is served to you, concatenated strings. Similarly, underscore
underscore Elian underscore underscore
is another chef. He's called for work when you ask the length
of the string. Works in kitchen and you are returned with
a desired output. Hence you don't see
these special methods in user interface, but they work silently
in the back end. These special methods with double underscores
on both side are called Dunder method or magic methods as they
work behind the scenes. I think your fear
is resolved now. Similarly, I use DR function on the list to get the list of
methods available for a list. Now we don't need to
remember any methods. DIR has returned the list
of all methods of a class. Do the programmer is happy now? How can this be possible? Programmer being humans,
our demand never ends. DIR has returned a
list of methods, but is there someone who can explain how to use
each of these methods? Python know about us very well. He has granted that too. Do you remember our old
friend help or forgot him? Just use same help function
with your instance, Python explain how to use each
of the methods available. Python gives all possible help to develop the good program. If you're looking for a function
that write the program, then sorry, Python
don't have it. By now, you must have realized OP is core behind all
concepts of Python. Even the libraries are
created with the OP. For example, math is the library we have discussed
in the previous chapter. Import math and ask Python
what type of class is math. You see its module. Module is a special class
of Python that allows user to utilize its
objects by importing. You can see the list
of all methods stored inside the math module
using Dire function. You might be familiar with
few of these methods, but some like this dist
we have never met before. Tell help function that I have met a stranger
in the math module. Can you please help me to get
to know about this method? Help function says, relax. Distance return the
Euclidean distance between two points along
with the formula. Learn it if you want and
it is relevant for you. If you have nothing to do with Euclidean distance,
then forget it. Not just math, all
Python libraries are instances of class module. That concludes the
current session. I'm very sure you have felt
OP easy and interesting. You have much more interesting
things to learn in OOP. You have seen the built
in classes of OP, but there is no much
thrill in using the classes defined by
the Python developers. Real adventure is
defining our own classes, instances, attributes, and
much more and play with it. That must sound
exciting for you. In the next session, we learn to create the object
classes of our own. Let's meet and explore together more interesting things
in the next video.
39. Defining Objects: Welcome back. In the
previous session, we have learned about fruits
more than any botany class. In this model, we teach
computer what we have learned. I mean defining objects. Let's not break the flow. Take our favorite example fruits because fruit is something
almost everyone knows. Is there anyone who
don't know about fruits? If by chance there is someone, then there is high probability
that either person is new to the English language
or new to this planet. Define the class fruits, just like you define function. But with the keyword class, class fruits and end
the line with colon. Just telling Python, there is class of objects called fruits. We define other
details like instances later for now pass the
statement to continue. What is this pass? Pass is a keyword that
absolutely do nothing. Strange. Why do we use
something that do nothing? Sometimes we need
someone who do nothing. We are alone, we
feel to have someone just to spend time with
us and nothing else. Pass is such a companion, use it as placeholder
for future code. If there is nothing to be
included in the body of a function or a loop or a
class or even if statement, pass can be used to tell Python, I will provide the
other details later. That is because you cannot leave the body of a function
or a loop empty, pass can be used to avoid
getting error. Is it clear? These lines. Now
Python know there is a class of objects
named fruits. Now define first instance of
fruit class. That is apple. If you don't like apple, you can define mango. I
have no objection. When we define an instance, first ritual you need
to perform is to tell Python that this instance
belonged to fruit class. Who on Earth do not
know apple is a fruit? Computer don't know because
it never went to market. Now Python understood,
Apple is a fruit. Now we shall define the
attributes of apple instance. That is property that define
the particular instance. I will define two attributes, color and taste. Let me define. Apple dot color is assigned with red and apple dot taste
is equal to sweet. This is like
defining if you find a red fruit with sweet taste, then it is apple. I know two attributes are not sufficient to explain
any instance. Once you learn OOP, you can define all
the other attributes if you have time and patience. Now for the sake of learning, two instances are good enough. Similarly, I define another
instance, fruit orange. The color of this
fruit is orange, same as its name,
and taste is sour. Have defined two instances
with two attributes each for fruit class to extract any
attribute of any instance, print orange dot taste. Similarly, apple dot color. You get the dessert details. Let's define a function for making the
introduction of the fruit. DEF function name introduction
and parameter is self. Self is very
important term in OP. Self is the keyword used in OOP to represent or indicate
or point the instance, whichever the fruit taken into
account for this example. This function take instance
name that is apple or orange for the fruit
example as argument. In the body, print this
fruit is curl Brass in color and curly braces in taste the format
self taught color, which translates to
instance taut color and self taught taste or
instance taught taste. Function is defined. The request a function
introduction to introduce orange.
You get output. This fruit is orange in
color and sour in taste. If you check for Apple, it prints this fruit is red
in color and sweet in taste. This function is boring and
something we know already. We need to learn something new. Are you ready to see a magic? Using the magic, I convert this function into a
method, dot notation. Move the same function
inside the class fruits. Important instruction is take
care of indents properly. Tell me guys, do we
need pass keyword now? We have left pass here because class fruits was
experiencing loneliness. Now class has body, so no need of the pass. He can go home now.
This magical step convert the function
into method. Now introduction is not
function, it's method. Run it again and write apple dot introduction and no need of any arguments inside. Self is not parameter now, but representation of instance, but it is mandatory to
use self. Execute this. Output will be same
as that of function. So you understood how to define a class instance,
attributes and method. This is one way of
defining the object class. After using the same
method for a few days, we feel boring and
search for new methods. So there is one more method
to define the class. This is called
constructor method. Name seems to be beautiful. In last two sessions, we had enough fruits. Let's stop the fruit fasting. In this example, we shall
work with the integers in the class to give equal chance and opportunity to numbers. No, constructor is not
biased to integers. You can try with the
other datatypes too. For this example, I used
my old friend rectangle. Now, you tell me what are the attributes or properties
that define ctangle? Rectangle is always defined by its length and
breadth or width, so they are the attributes. Let's start to construct the object class using
constructor method. We define the class name with the statement class rectangle. This is the same as what
we have done before. Now we need to define the
attributes of the glass. For that, we use DEF underscore underscore
init underscore underscore. That is saying, I'm initializing the attributes with the
parameters first and very important self
which indicate the instance followed by attributes name,
length and width. In the body, we assign self
taught length is equal to length and self taught
width is equal to width. Know these lines
sound bit weird, but there is a
logic behind this. As we define while initializing, user provide two parameters
while defining the instance. Self itself is instance, hence length and width are provided by the user as
parameter or argument. Somewhere like this in the order first length
and then width. We are telling Python
that user while defining the instance provide you
two values as parameter. That will be in the order
of length and width. What you, I mean, not
the Python have to do is assign the value of
parameter length provided by the user into self that is attribute dot length and parameter width to
self dot width. You understand,
great. If you don't, then don't mess your head. I will explain when I
define the instance. We are done with defining
the object class and its attributes. Now I define
instances named plot. In fact, multiple plots which
belong to class rectangle. This is how instance is
defined in constructor method. It may look bit messy, but once you understand,
it is very easy. Plot one, plot two, plot three, and plot four are four
instances of class rectangle. The two values they're
having are the attributes in the form of parameters in
the order, length and width. We have defined
three parameters, but self is instance enhance pass two parameters,
length and width. Now tell me, is this clear? Make sure you understand this. If yes, as I promised, let us make it clear for
audience with the confusion of what the self taught
length is equal to length. You can understand it
now. Each rectangle is defined by two parameter
ignoring self length and width. Per this definition,
for instance, plot one, three is length
and four is width. Agree. What these
two lines mean is, we are telling Python, user has provided two values. You assign the first value, which is as per
the initialization is length to self at length. Assign second value
to self taught width. The value three and four
provided by the user as parameters are assigned to the attributes length and width. Isn't it simple?
Now we have defined four plot instances belong
to class rectangle, defined by their
length and width. Now I define a function to calculate the area of the plot. With one argument, I
named it as ground, which is an identifier for the instance of the
rectangle glass. Area is calculated by
multiplying the length and width of the instance ground
belonging to the rectangle. As usual, return the area. So our function is defined. Now calculate the area for all the defined plots belonging
to the rectangle class. When you run it, you
get the desired output. I don't want function area. Instead, create for
me the method area. That's not a big
deal for you now. You have learned the magic to convert the function
into method. Same as we did before. Move the function
inside class rectangle. But let go the identifier ground and replace it with self. When you define method, always use self to
represent the instance. Nothing more to
do. Magic is done. Now you're ready to give
the stand up magic show. Run the code and enjoy
using the method area. I will check plot one dot area. Great. As the concepts in this session can
create confusion, we are going bit serious. If you have understood till now, we can switch back to one more. Let's try to learn
just one easy concept before we end this session. You have mastered the art
of creating functions, I don't worry much and I will
create a basic function, define ad ACAB, and in the
body written A plus B. Here is a simple program
that add two numbers. I have created the program
and you have watched it, so we know what this
add function will do and how many arguments
the ad function will take. But think of the user. No one will come in his dream, like we heard in the
stories to explain how to use the function and
what parameters it has, or even how many
parameters it has. Because for the front
end or user interface, program will not be visible. When we don't know how to
use built in functions, help function used to come for our help like mom
and explainers. We shall ask the same
help function to help us with the defined
function, help add. Help function will help you, but help function just written the arguments or
parameters only. That is very plain meal
without any salt and spices, and that is obvious. What else you expect? We have just taught Python
how to cook the recipe. How in the world, poor language know what exactly we
are intended to do? It is not mind reader. It is again, our
responsibility to make the information from help pleasing and easily
understandable. That is achieved
using doc string. By now, you must
have realized that complicated terms need not be
having complicated meaning. In easy term, we can say
providing more information. But when we use the
term docstring, people will think this person has a lot of
technical knowledge. Instead, if you say providing more information,
seem to be normal. That's why we use complicated
term for simple concepts, and doc string is something
we have used already, but now making it more useful. You have learned already to comment using the triple codes. Do you remember that? Then you have nothing new to learn here. Doc string, the cool looking
term is nothing but using the triple code to explain what a function does
inside the function. For the example, I
will add statement, this is the function that
returns the sum of two numbers. Depending on your function, you can add any information. Take multiple lines if you want. I have written
almost same things into lines because I have
nothing more to add. Now go and check the
help function again. Help function now helps
very well as its name. The same concept of Dx string is used while
defining classes. Add Dx string to
fruit class saying fruit class define the color
and taste of various fruits. Okay, now check help fruits. So it gives some
information for the user. Isn't it easy and
simple to understand? To conclude, doc string is the piece of text
information that is left for the user of the program
to explain what a function or class
does and how to use it, and it can be accessed
through help function. How is Opie going on for you? Is it easy or confusing? My suggestion at this
point is practice creating object class with
your own examples before going through
the next lesson. Next session is
beautiful forest. If you proceed with
proper understanding, you will enjoy the
serenity of the forest. If you go with the
half knowledge, it is easy to feel
lost in the forest. Step into the forest
with proper preparation. Let's meet in the Opie forest.
40. Inheritance: Welcome to the beautiful
forest of OOP concepts. You may spot wild
animals here and there, but they're very friendly. You will experience
variety of concepts here. After going through the
two lessons in OOP, I hope creating any object has become left hand
game for you now. Let me make you use your
right hand tool in OOP. In this session, we learn
the key concepts of OOP. They are inheritance,
encapsulation, and polymorphism,
beautiful terms that are capable enough to
cause fear among the audience. These terms are more horrible to hear than the horror movies. But we have surpassed many
such horror movies earlier. We have developed a kind
of power in this lesson, we convert those horror
movies into romantic movies. Are you ready? We can't
fix all of them together. Let's handle them one by one. The first concept
is inheritance. I hope this term is not
strange one for you. Do anyone told you ever you inherit some feature from
either your father or mother? Not necessarily good
characteristics, I know. Sometimes we inherit bad
characteristics too. What to do? We don't have any choice to choose only good features from parents and another important and exciting
example of term inherit, you may be having the property inherited from your ancestors. How can you forget
that? That means you know inheritance already. Are very cool guys.
You make my job easy. Meaning of the word inheritance
is driving the quality, characteristics, property, or asset from one's
parent or ancestors. In even simple term, all good or bad
things derived from the ancestors are called
inheritance. That's okay. We understood the term. But what genetics and law
has to do in programming? Are discussing this because even Python class has
parents and children, even they deserve a
good loving family. Don't worry much.
Consider simple example. We have mango class
and varieties of mangoes like
AlfonsHydn Atkins, Neelam, are instances
of mango class. The twist is mango has parent and you don't need to perform DNA test
to know its parents. Class fruits that we have discussed in
the previous session is the parent of mango
class. Big secret here. When we think of fruits, at least few characteristics
come to our mind. It's grown in trees, has pulp, seeds, outer cover,
it's delicious to eat. It's loaded with nutritions and health benefits, and much more. These are the characteristics
of fruits, and mango, being the child of fruit class, inherit these properties in it. Just like us, mango has
some unique features too, along with the
inherited features like distinct color and odor, and that differentiate mango
class from its siblings. Yes, mango class has
brothers and sisters too. By now, you must have
understood their names. They are apple class, orange class, strawberry
class, and so on. All these class inherits
some properties from fruit class and have their
own unique properties, and fruit class has sibling too. Maybe his name vegetable class. I don't know. I'm not
their family friend. Vegetable is uncle of mango. We shall not make such
complex relationships. But these fruits and
vegetables inherit the attributes from class
food or something else. Is there any difficulty here? Nothing. We eat fruits
and vegetables daily, but we are finding unseen
relationship among them. I hope it's clear for you now. You guys learn very fast. What do you eat to
become so smart? Fruits and vegetables? Okay. You already understood
inheritance. Now let us learn how to
apply inheritance in Python. In the current example,
we define class vehicle. Anyone automobile enthusiast
here, you can say, yes, I don't ask you
a question about it because I don't
know much about it. If you don't know about it,
I can talk more confidently. I have a disclaimer for
automobile experts. This is for education
purpose only. All vehicles, say
truck, bus, motorcycle, car are individual
child classes of vehicle as per the
definition of inheritance. Don't ask me later, when
each of these children born, it's all their personal matter. When we say vehicle class, they are defined by
hundreds of attributes. I think you know it better. I define two
attributes among them. DEF underscore underscore init underscore
underscore self, which is attached to all classes and I
define two attributes. One is fuel, defining which
fuel it used to get energy, petrol, diesel, energy drink and something else
that I don't know. Second attribute
is transmission. If it is manual or automatic, or you can mention particularly which type of automatic
transmission. Depending on your time, you
can define other attributes. Let us follow the
rituals of explaining the attributes that we
do for all classes. It is one of the easiest thing
one can do in this world. Self dot fuel is equal to fuel and self dot transmission
is equal to transmission. Is there anything else
easier than this? Attributes of the her
class are defined. Define a method for Wehle class. When there is a vehicle, then it has to
turn on to use it. Otherwise, it's just a
toy or scrap, turn it on. Define start self. When user gives start
command, vehicle must start. I'm not automobile engineer, so I cannot make the car
switch on just by programming. I just print engine
started, ready to go. You must assume engine has
started and ready to go. We have defined the
method for vehicle glass. Now it's time to define
the child of weaker class. Even though there are tens
of children to weaker class, I cannot define all of them. I define one that is car. This is the most
popular child of gel. Very important step while
defining child class car. Don't forget to mention its father name in
the parenthesis gel. Op now knows that car is
legal child of weicer class. Being the legal child, class car has a right to inherit all properties and
method of weaker glass. No one can question it. When it has the legal right, class car can even take all the attribute from
the weaker class. Weaker class has only
two attributes and car has access for both
attributes of vehicle. But if child wish to consider
one, it is most welcome. But when we have option for two, why should we consider one? Define the attributes
of class car, same as you do for
all attributes. Define under scosce
int under sconoc self, fuel and transmission
which its father had along with that car has unique
attributes with sunroof. With sunroof, define if the
car has sunroof or not. If the car has
sunroof, value is. It's I mean programmer's
responsibility now to tell Python that fuel and
transmission are inherited. OOP already know vehicle
is parent of car sort super dot underscore underscore init underscore underscore,
fuel and transmission. Now OOP understood, CR is taking both attributes from
its parent vehicle class. Then what about sunroof? Sun roof is car's
unique feature, so define it like
other attributes. Self dot sunroof is
equal to sunroof. Even though car
class has inherited attributes and method
from its parent, everyone has dream of having
something of its own. I will define a
method for car class. Not every vehicle has
air conditioning. We have air condition
in motorcycle, but car has define
method to switch on AC, which will print AC is on now. Again, you assume
AC has turned on. Enjoy the cool breeze
from AC or imagine so. Car has access to its parents
attributes and method. Along with that, it has its own attributes and methods too. It is privileged class. I will define an
instance my car, which is a car with
attributes, fuel petrol. Transmission automatic
and with sunroof, yes. Fuel is inherited property
from class vehicle. Let me print mycar dot fuel and let me try both
methods, car dot SAT. This is an inherited method from its parent class vehicle. Along with that, I will
use cars own method, car dot switch on AC. Now both engine and AC
turned on or assumes. This is how attributes
and methods are inherited from
parent to child class. If you want to know
how to inherit the properties from
your parent class, you need to consult
your nearest lawyer. Python cannot help
in this regard. We have converted
one horror movie into romantic jolly ride in car. I hope you felt
inheritance super easy. Same goes with the next concept that we are discussing
in next lesson.
41. Encapsulation: Second concept we are exploring in this lesson is encapsulation. The fancy word sound like encapsulating you
inside confusion. No, it's not that
complex as you think. It's easy concept that
you know very well. Assume you have some
confidential document or note with passwords,
how will you handle it? If that was me, I would keep in such a safe place
that even I search for it later when I need we don't keep them
open in public place. When you have some private
document or information, first thing we do is wrap it
inside cover or back so that the information is
not easily visible outside and then lock them
inside the safety drawer. That means you keep it covered or encapsulated to
hide from public. Only you or your authorized
trustworthy person, maybe your parent or business partner would know
how to access such data. This is something we are
doing since childhood. We used to hide things
from siblings or elders. What you used to hide differ
from person to person, but the thing is
we have done it. This simple concept
that we are doing since childhood has the fancy
term called encapsulation. Simple term, encapsulation
is hiding from the public and giving access
only to authorized person. In VOP terms, encapsulation is
controlling the access of the object class. No matter how much
we say about it, you will understand when
we use it in example. Let us see how we
do that in Python. For this concept, let me
define class bank account. Bank account details is
something you do not scream. This is my account number. This is balance, and
this is my password. There is no need to
keep balance private, but no one like to insert
themselves showing balance. All this information
need to be private and accessed only by you and
other authorized person. Let us define two attributes, account number and balance, and both these details
must be hidden from public and access it privately by you or
authorized person. So both these attributes
need to be encapsulated. There is a way to
secretly tell Python that the attribute is confidential
and need encapsulation. Provide double underscore
before attribute. Self dot underscore
underscore ac number is equal to ac number. Now OOP no account
number is confidential, and it cannot disclose
your balance too, self taught balance also
need encapsulation, so provide double underscore. We have defined the instance
and encapsulated it. Now encapsulation
does its job too well that it don't even
disclose the details to you. You cannot access or modify the values at any
cost or influence. If you don't trust me, check it by yourself. I define an instance, my account, which is
class bank account. I need to enter account
number and balance. This is top secret. No one could say it, but
I'm sharing it in public. My account number and
balance is defined. I assume you have
not watched it. You can assume yourself,
which currency it is. Now access my account dot Balan. Python say there is
no such attribute. Check underscore
underscore balance if you think that may work. No, just by giving
double underscore, Python understood very
well that data is confidential and Python is
good at keeping secrets. It says there is no
such attributes. Good job, Python. Today, I have understood even Python
lie, but for good cause. Python don't allow
anybody to see the details and no one is allowed to modify
the details, even you. What we must do is allow the VOP to access the
details in controlled way. I define a method, credit. I want to credit some
amount to the account. Self amount and add the
amount to the balance, you need to strictly
use double underscore. Self taught underscore
underscore balance is equal to self taught underscore
underscore balance plus amount. When you add the amount, there must be a way
to even withdraw it. Similarly, another method
debit to withdraw some amount. But what if guy tried to be over smart and try to withdraw
more than the balance? For that, put if condition, if amount is greater than self dot under
scronoscoe balance, you need to tell
insufficient balance, else, otherwise, deduct the
amount from the balance. That's all okay. But Python, don't allow me to even check the balance. How can I check it? You need to create a private
method to check that. Define check balance
with no argument, only self, and return the balance in the
style of encapsulation. Self dot underscore
underscore balance. This is called accessing
and operating in controlled way if you have
feared hearing these terms. Now I define my account
with 2000 units balance, and then I will credit
1,000 units more. I can add any amount just by typing values here
even in millions, but I don't want to
make joke of myself. Now, what should be the
balance? Is it worked well? I will try to withdraw 4,000 units and want to check balance. Python says insufficient
balance in front of me. Don't know how it
reacted inside. No change is done for the debit, hence balance should
remain 3,000. Now tell me, guys, is there anything called difficulty
in these concepts? They are just creating the panic using the
high standard words, inheritance, encapsulation, but they are very easy concept. Shall we move to
the next concept? It is encapsulated
inside the next video.
42. Polymorphism: The last concept we
are learning in OOP, which is also very simple but horrible to hear
is polymorphism. Doesn't it sound like something used by doctors or biologist? If you felt so, you have
got pretty good intuition. Yes, this is a biology term. Chance is there anyone from biology background
among the audience, then they know the meaning
of this term very well if they attend their class
and I assume they did. If there is no one here, then I can speak with
more confidence. In biology, polymorphism
is state in which an organism that can
exist in different form, that doesn't sound cool
for non biologist. Don't make it
unnecessarily complex. It is the simple task that we do almost every
day except Sunday. Have you ever been multitasker? Sometimes we need
to be multitasker when we are balancing
the home and office. You may be cooking
or doing other work at home while attending
the office call. Yeah, I know, and I don't tell these secrets to your
boss or professor. Moreover, even they
do such multitasking. Don't you think they
are human beings? You perform multiple roles
in your life every day? You are a programmer when you
sit in front of a computer, Chef when you are in kitchen, strict s to reportees obedient
husband in front of wife, sleeping monster on Sunday. We play all these characters
being just one person. This simple concept is
called as polymorphism. In Python, polymorphism is
using the same function or method inside different class to return different outputs. We shall see how we do that now. As the term polymorphism
is derived from biology, we consider example from
biology, precisely from Pharma. I know you hate medicines, but in modern days, people started to consume
more medicines than foods. These medicines have
different class. We use different class of medicines for
different problems, like in technology,
even they use fancy difficult to digest terms
for even simple concepts. I will define few of
the class of medicines. Start with defining
the class analgesics. I don't define any
attribute here. We already learned how
to define attributes. I don't want to repeat
it again and again. Scope of this session is
to learn polymorphism. I directly define a method, what it does, to define what
it does as its name says. What analgesics do
is relieve pain. I print that. If you feel headache after
learning any concept, you can go for analgesics, but only after consulting
your physician. We have defined one medicine, define another class of
medicine, antibiotics. Even it has say method, what it does that print
treat bacterial infection. The method, what it does is not the private property
of analgesics, even antibiotics take it. That doesn't end here. The next class antipyretics, also use what it does. What it does is reduce fever. Finally, antihistamines
that treat allergic reactions also
has method, what it does. Now we have four class. Now I will provide
one instance each to these classes that
are commonly used. You can define more if
you are pharmacologist. For analgesics, I
assign ibuprofen. Azithromycin for antibiotic. For antibiotics, let's take paracitomol and finally, tysin for
antihistamines. These are not my prescription for any health
issues, by the way. In polymorphism,
the method is same. That is in this
example, what it does. The same method is used
by multiple classes. The method, what it does
is a multitasker like. If you ask parasitamol
dot, what it does, Python first check which
class parasitamol belongs to. Acetamol is antibiotics, so it return the
method of antibiotics, that is reduced favor. If I ask what do azytomycin do, it reply treat
bacterial infection because it is an antibiotic. The method is same, but
applicable for different class. Such state of
method to exist for different class is
called polymorphism. Again, I asked the
same question, is there anything
difficulty here? No concept in this
world is difficult. We make it
unnecessarily complex. I want to conclude
one thing for you. Complicated looking term might
have very simple meaning. How is your learning journey? We have come to the
end of the course, but the new beginning
of your Python journey, see you all in farewell party.
43. Last Note: Welcome back. And this isn't
just any regular session. This is not the technical
session like previous ones. But the one where we are going to celebrate your
commitment to learn, you made it to the end. This is the time to
put on the party hat. But seriously,
feel free to treat yourself later because
you have earned it. First thing first, give yourself
a big pat on your back. You seriously deserve it. You have traveled all this
way through data types, conquered loops, tamed
functions, and batted bugs. How was the journey
if you look back? I hope you have enjoyed
learning new things. Now that you have reached
here the end of the course, you might be wondering,
what's next? You have finished the course. Does that mean you
are done with it? This is actually
just the beginning. Think of it like this. You have finished first
level of the video game, and as the reward for
unlocking the new level, you have got a sword. That is your Python skill. Have got a new weapon. Before you build the next
Instagram or Netflix, you got to sharpen
your new skill. But how can you do that?
There is a secret to sharpen your programming skill that is not a secret anymore. Here is the key to take your
coding skill to next level. Practice in the
online platforms, I suggest you to practice
problem solving in competitive coding
platforms like HackerRank, code chef, Hacker Earth or any other popular
coding platforms. If you're particularly
interested in data science challenges,
practice in Cagle. This step is very important. These online coding platforms are like the gyms
for the programmers. It is where you get to flex your coding muscles and learn to solve real
world problems. While also competing
with others. You are not expected to maintain the great rank from day one. It is not just about winning, it's about learning,
growing, and leveling up. Every problem you solve, every error you fix is like
leveling up in the game. You get stronger,
you get faster, and you get better. It will improve your
problem solving skill, increase speed and
efficiency of your coding, increase confidence, and
last but not the least, it will help you to crack the programming challenges
of recruitment process. But I want you to remember
something that is really important for a
programmer. Don't rush. Coding is a marathon,
not a sprint. It's okay if you make mistakes. It's okay if you get
stuck with the problems. The key is to keep going. Take your own time,
learn at your own pace, and most of all, don't
forget to have fun. Whatever you do, enjoy it. And when it comes to Python, it is not just a tool, it's also your playground. You can play around, experiment
the odd idea you have, and enjoy it to the fullest. Let's talk about community. Even this is important
because let's be honest, sometimes coding can
feel a bit lonely. You will feel like
it's just you, your computer, and
that annoying bug that just won't go away. It can be frustrating sometimes. I will suggest you to find
a body or group of people. You're not at all alone in
this technology driven world. There are millions of coders out there, maybe just around you. They are just like
you, learning, struggling, and
celebrating their wins. Find them, join
forums, find groups. Once you get them, ask questions
and share what you know. You will elevate
your skill level while helping others to
solve their problems. Whatever comes next on your way, whether you're starting
your own project, doing coding challenges or maybe even getting
into data science, I want you to remember, coding isn't just about
writing lines of code. It is about solving
problems, being creative, and having the courage to keep trying even when it gets tough. I strongly hope you will shine like a charm in
programming world. Always excited to
see your success. If this course has laid at least 1 stone to the
foundation of your success, that fulfills the
purpose of this course. The digital world is small and
our paths may cross again. Maybe in next course, or maybe I will hear about something amazing
you have built. Until then, keep creating and most of all,
keep having fun. At the end of the day, you must enjoy whatever
you are doing. Thank you so much for being
with me on this journey. Now go out there,
make some magic and remember quote like
nobody is watching. Love you all and
Bye bye for now.