Computer Programming Lang...
Computer Programming Lang...
Languages: 2 books in 1
For beginners or intermediate.
A step by step guide to learn C, C#, C++, SQL and Python
and
By Tony Chan
The content contained within this book may not be reproduced, duplicated or
transmitted without direct written permission from the author or the
publisher.
Under no circumstances will any blame or legal responsibility be held against
the publisher, or author, for any damages, reparation, or monetary loss due to
the information contained within this book. Either directly or indirectly.
Legal Notice:
This book is copyright protected. This book is only for personal use. You
cannot amend, distribute, sell, use, quote or paraphrase any part, or the
content within this book, without the consent of the author or publisher.
Disclaimer Notice:
Please note the information contained within this document is for educational
and entertainment purposes only. All effort has been executed to present
accurate, up to date, and reliable, complete information. No warranties of any
kind are declared or implied. Readers acknowledge that the author is not
engaging in the rendering of legal, financial, medical or professional advice.
The content within this book has been derived from various sources. Please
consult a licensed professional before attempting any techniques outlined in
this book.
By reading this document, the reader agrees that under no circumstances is
the author responsible for any losses, direct or indirect, which are incurred as
a result of the use of information contained within this document, including,
but not limited to, — errors, omissions, or inaccuracies.
BOOK 1: Computer Programming for Beginners:
C, Python, SQL
Table of Contents
Introduction
A Look at C
Getting the IDE
Writing a Dummy Code
Writing Out Loops
Do/While Loop
The Nested Loop
The Variables
The C Functions
A Look at C++
Creating Our First Code in C++
The C++ Variables
The C++ Arrays
The Switch Statement
How C# Is Different
The C# Data Types
Creating a Class
Creating Objects
The C# Constructors
The C# Loops
Conclusion
Table of Contents
Introduction
Conclusion
References
Introduction
Congratulations on purchasing Computer Programming for
Beginners: C, Python, SQL, and thank you for doing so.
The following chapters will discuss all of the different parts that you
need to know in order to get started with your own programming goals along
the way. There are so many different parts that come with programming, and
so many people want to learn the basics, but many worry that it is not going
to be easy at all to learn or that they just won’t have the time. With the help
of this guidebook, we are going to take the time to learn not just about the
basics of computer programming but also more about how to get started with
working on five different coding languages in no time at all.
From there, we are going to take a moment to talk about the three
main operating systems, Mac, Windows and Linux. All of these have some
benefits that make them the perfect option to work with, but it is important to
know more about what you want to accomplish with your coding, and your
ultimate goal at the end as well. We will discuss how this works and what we
are able to do with each of them when it comes to coding.
Then it is time to get into some of the fun parts of coding and what we
can do in this guidebook. We are going to first take a look at the C languages,
including C, C++, and C#. These are all great languages that share a lot of
similarities, but there are also a few major differences, which we will spend
some time discussing in this section. We will look at how to write codes in
each one, how to handle the variables, functions, and more so that we can
start writing some of our own codes in these languages in no time.
After we have had a chance to learn to code in the C languages, it is
time to move on to how to work with the Python language. This is a great
language that a lot of programmers like to spend their time on because it not
only has a lot of power to make coding as easy as possible, but it is also
designed for a beginner. This makes it the perfect option to learn in a day or
less, and with all of the potential applications, you are going to be able to
make this work for your coding needs, no matter what those are. We will
look at a few of the most common ways you can work with the Python
language, including how cool it is as an OOP language.
Finally, the last language that we are going to focus on is SQL. This
one is a bit different than the others because it mainly focuses on helping us
to create, manage to analyze and more with our databases. But the language
is simple to learn, and we can get it down in no time at all, so it is definitely
something that we need to spend some of our time on.
There are so many great programming languages out there, but the
five main options that we discussed in this guidebook are going to be some of
the best that we can focus our attention on and learn quickly, in order to
accomplish pretty much any project that we would like to do in coding. When
you are ready to learn some more about computer programming and how to
get started with your own coding language in no time, make sure to check out
this guidebook to help you get started.
There are plenty of books on this subject on the market, thanks again
for choosing this one!
Every effort was made to ensure it is full of as much useful
information as possible, please enjoy it!
Chapter 1: The Basics of Programming
If you are looking for some ways to make your lessons in coding
easier, then taking the first step in this new world is going to appear really
intimidating and confusing. And in many cases, it is going to seem like a
really intimidating task. There is a big secret to help out with this, though.
There are going to be a ton of inexpensive and even free options that you are
able to use in order to teach yourself the coding techniques that you would
like to use and can make this learning process fun and exciting.
Whether you are an adult who is looking to learn more about coding
or you are looking to make a big career change, or even a student who is
wanting to really learn some more about the latest language out there that can
propel you to the future, or a hobbyist that just wants to learn more about
how these services and the software that we use actually works, then
programming is going to be one of the best ways to help you get going on all
of this. The good news here is that all that we really need to start our
programming journey is a computer and internet access as well. Before we
dive into some of the work that we are able to do with a few specific coding
languages, we need to start out with some of the basics of programming to
help us get started.
The answer that you are going to give out at this time is going to give
you a good idea of which programming languages you are hoping to master,
as well as the kind of commitment, in terms of money and time, that this goal
is going to require. For example, if you have the dream of creating your own
operating system or a new software program that can compete against
PhotoShop, you would want to go with more of a stronger language like C++
to help you get through some of the more complex topics that are necessary.
On the other hand, if you are in a professional career and you would
like to be able to move over to a more technical career, then you would want
to go with something Raspberry, Python, and some of the other options to
help us out. It all depends on what you are hoping to get done with that
coding language.
If you would like to work with a coding language that can handle
databases and provide you with interactive websites that will include things
like payment systems, then knowing how to work with Python, SQL, PHP,
and JavaScript to make this all happen. But if you would like to make an app
for mobile devices, then working with C or Swift will be one of the best. iOS
apps are going to be best with those two above, and then the Android apps
are going to do best with Kotlin and Java. Video game developers are going
to like C# or Unity to bring some of these ideas to life.
If you are still uncertain about which kind of coding language you
would like to work with, most professionals are going to recommend learning
how to work with JavaScript, C#, or Python to help out. This is because they
are going to open up the broadest career flexibility and utility. To help make
that decision, you have to consider what you hope to accomplish when
working with this kind of skill in the first place.
For those new programmers who would like to be in control over the
schedule they learn with, or they do not want to spend it all going through it
alone, then a coding course you can take online seems to be a much viable
choice compared to physically attending a boot camp for coding.
Nevertheless, it won’t be easy figuring out which ones are the best one
because there’s going to be a lot of online classes that are going to teach you
some of the great programming languages.
Often you are going to spend some time looking for ones that are
going to teach the particular language that you would like to learn and start
from there. Then you are able to spend some time looking for ones that offer
the schedule that you would like and are going to provide you with the
learning capabilities that you would like.
There is also going to be some lingo that you need to spend your time
on, such as loops, conditional statements, and exceptions that are bound to
show up all of the time, no matter which coding language you decide to go
with. The more that you are able to comprehend and go through these
ideologies, it’s going to be a breeze for you to learn the language that you
would like, and each subsequent language that you are able to work with
overtime is going to be easier as well.
Let’s face it, no matter how motivated you are to do some of the work
that you need to do with your chosen coding language. No one wants to
spend forever analyzing lines after lines of code on a book or on a screen.
This is going to be hard and boring sometimes, and if you haven’t had much
time to work with the coding, then it is going to look a lot like gibberish after
some time.
For example, one of the games or interactive tutorials that we are able
to work with is going to be known as FreeCodeCamp. This one is going to be
able to break down some of the coding concepts that we are able to work with
and turns them into smaller chunks that are going to show up in the web
browser that we want to work with along the way. It is also going to help us
to pair each of these concepts with an appropriate exercise that we need to
crack before we move onto the following topic. Rather than just trying to skip
to some of the fun stuff without learning, with this method, you are really
going to have to learn about the code and how to debug it as needed.
Coding games are also going to be one of the fun methods that we are
able to use in order to get our feet wet when it comes to programming. If you
have a bit of time to kill, and you want to practice your coding, you could
work with Hour of Code. Or there are a lot of schools that are going to work
with the program Minecraft: Educational Edition, in order to help kids, learn
some of the basics of programming, with coding blocks, and even some work
with JavaScript. There are a lot of options that we are able to work with when
it is time to learn more about coding, and turning the work into something
that is going to be useful for your needs.
The best thing here is to start small with the work that you are doing,
but you can think big. Your chosen project best involves some skills that are
already in your toolbox or knowledge base. You also need to have some kind
of plan in place for skills and future features that you may want to learn in
order to turn that vision into a reality that you are able to use on this project
and more.
Without being able to apply your coding skills to more than one
project, then you wouldn’t really be considered as someone who is able to
take on professional coding skills. This means that we need to go through and
do some planning and practice. When you have a few projects under your
belt, you will not only be better at the coding that you have been practicing,
but you will also be seen as more of a professional in the work that you are
doing as well.
Coding is going to be all about the details that you are able to work
with along the way. This is why it is so important for us to take in the
victories that we would like, and celebrating even some of the smaller
victories are going to be important. It is going to take a lot of practice in order
to make each element of this work along with the others and getting this to
work without any kind of mistakes. If for some reason, you do not do
something that seems minor, for example, closing the tag of HTML, you are
going to spend a lot of time debugging a simple error in the syntax, rather
than taking the time writing more impressive and complex codes as you go
through it.
You also need to make sure that you maintain patients with yourself
as you go through this. You do not expect to code the next Fortnite or another
project that is big and successful with just a few boot camps or just a small
amount of time studying. Creating a number prediction game that’s simple,
but accurate, or an error-free coding of a wedding RSVP form on a website is
going to actually be a really significant achievement for someone who is a
beginner.
So, even if you are working with some of these smaller options, in the
beginning, you should not feel bad if you do get stuck. Don’t use this as an
excuse to give up at all. And you should know when it is time to take it easy
to dodge any of the burnout that should happen, as well as always seek for
assistance anywhere accessible, and go for it again until you get it right.
This is actually something that can help you out no matter what kind
of coding language you are going to work with. If you are going through the
coding and you are not sure why the code is broken and why it is not working
the way that you would like, you can always go through and find some of the
solutions that will make this easier online. It is likely that other beginners are
going to have the same kind of mistake along the way, and if you just copy
and paste the error message into a search engine here, you should be able to
find some information on that error.
This is going to make it a lot easier for you to figure out what is going
on with your code and will ensure that you are able to learn and fix the issue
all at the same time. If you are still running into trouble when it comes to this,
you will then be able to post your question on some of the forums that you
want to work with, including GitHub, Stack Overflow, and more.
While all of the tips that we talked about above are going to be great
for helping you to learn more about coding, it is important to learn the
number one trick to getting this coding down in no time at all. If you are
really dedicated and use some of the codes and information on the codes in
this guidebook, you can even get to learn it in one day!
The trick here is to get your hands dirty and actually start coding. You
can spend as much time as you would like looking through books and texts
and websites about these codes, but until you actually open up the compiler
and start typing it all in, you are going to be behind. The more codes you can
type out and practice, the faster you will learn.
It may seem like this trick is too simple, but it is truly all you need to
make sure that coding comes to you easily, and that you will see the best
results with it in no time. Simply choose which language you would like to
learn out of this guidebook, take the time to read through that section, and
then actually get out there and start typing and practicing some of those
codes, and you will be set to go.
To start with, we can look at SQL and Python. SQL is a language that
is designed to interact with many of the databases that we rely on. It can help
to create, modify, adjust, delete, and more the many databases that we rely on
for our organization. On its own, it can add in a lot of power to the database.
But we can also combine it together with Python to get something even
better.
There are so many reasons why we will need to spend time learning a
programming language. And we can spend all day talking about the benefits
of learning how to code. This can help us to learn more about our computers,
helps you to find a new career path and more. But the main question we want
to look at is why each of these languages is so important, on their own, to
learn.
Next on the list is the Java language. This one is able to help with a
number of the programs that you would like to learn about. But it is
especially known for helping out with creating websites. While any of these
languages, with the exception of SQL, can be used to help create websites
and manage them, none are able to handle this as we see with Java. This
language is set up in order to make these websites high class and impressive
and even adds in an element of interaction to this as well.
And finally, we reach the SQL language. If you are a business that
deals with databases at all, then the SQL language is the one you need to
spend some time with. This language was designed to help with all of your
database needs, from creation to modification, deleting, adding, and so much
more. The other languages can sometimes help with this, but it is going to
really be the SQL option that makes this work well.
There are a lot of cool things that we are able to spend time on when
it comes to learning more about programming. We are going to spend some
time looking at some of the best options that will help us to get better with
some of the work that we are trying to do in coding. Let’s dive right in to get
started!
Chapter 2: The Different Operating Systems
The next thing that we need to spend some time on is the operating
systems that we are going to be able to work with to do our programming.
There are three main operating systems that we are able to spend our time on
to help with programming, including the Windows, Linux, and Mac operating
systems. Let’s take a look at some of the different benefits and features that
we are going to be able to see with each of these operating systems.
The first operating system that we are going to work with is the
Windows operating system, designed by the Microsoft company. This is a
system that is going to allow you to get onto many of the computers that are
designed and will be found preloaded on many of the new personal
computers that you will want to work with, which is part of why this is the
most popular operating system throughout the world.
The Applications
An application, which is often going to be known as a program in this
operating system, is going to be a type of software that is going to allow you
a way to complete some tasks on your computer. Windows is going to come
with a lot of built-in applications that we are able to use. So, if you would
like to work with Microsoft Edge, you can open it up and start browsing the
internet.
To help us out, we need to work with the parts of a window. You will
see that there are going to be the three types of buttons that are on the upper-
right corner of all windows that you work with. These buttons are going to be
there to make it easier to perform a few different functions. These will
include:
1. You can click on the Minimize button in order to hide the window.
This window is going to be minimized to the taskbar. You are then
able to click the icon for that window on the taskbar, and that will
have the window show up again.
2. Click on the Maximize button so that the window will take up the
whole screen to make it easier to work with.
3. If you have the screen maximized, then you will find that the
Maximize button is going to be changed to the Restore button
temporarily. You can click on this button to get the window to go
back to the original size that it should be.
4. Then the final button is going to be the Close button. This helps
you to close up the window and move on.
Another thing to work with is resizing the window. You can hover the
mouse so that it is over any corner of the window, then click and drag the
mouse in order to make the window turn bigger or smaller. When you are all
done, you are able to release the mouse. The window can then be resized to
the size that we would like it to be.
If you are using an older version of this, like Windows 8, you will need
to click on the Start button to help access the Start screen, click the Power
icon near the upper-right corner, and select Shut Down. If you don’t see this
kind of option, it means you will need to upgrade to Windows 8.1 to get it to
work. But if you are working with Windows 7 or an earlier version, you can
click on the Start button and then select the option for Shut Down, and the
computer will turn itself off.
And the final benefit that we are going to look at is that Windows is
going to be able to match up with the other products that are available from
Microsoft as well. this is going to ensure that we will be able to see some of
the benefits that we want in no time. You will be able to work with the
internet option of Microsoft, Word, Excel, and other similar products, which
can really make your life a lot easier.
The first thing that we need to explore when it comes to the Linux system
is the three main components that make it up. These are going to include:
Run Level
The second thing that we need to explore is the run level in this system.
The run level is going to be a mode or a state that is found in this operating
system. There are going to be seven of these, and they are going to be
represented with a single-digit integer. It is going to be one of the most
important things that we need to learn in Linux. And the kernel that we talked
about before is able to differentiate and support all of the levels. The second
run levels that we need to explore when we are in Linux will include:
1. The run level 0: This one means that the system is going to be in its
haul state, with no activity going on.
2. Run level 1: This means that the system is in the mode for a single
user. This one is rarely going to be used.
3. Run level 2: This one means that the system is in the mode for
more than one user, but there will be no network file systems
present at all. This one is often not used either.
4. Run level 3: This means that the system is being used in the
command line mode with multiple users. This is going to be the
default run level that we will find on most of the systems that use
Linux.
5. Run level 4: This one means that we are in a mode that is going to
be defined by the user. This is another level that is not used all that
much.
6. Run level 5: This means that the system is going to be in the mode
for multiple users, but the GUI is in place, or the graphic user
interface. This is going to be another standard run level for many of
these systems that we work with, as well.
7. Run level 6: This one is going to be used any time that our user
would like to be able to restart the system to help with a reboot
when things are not working the way that we would like.
And these are just some of the starting points of when you are going to
work with the Mac Operating System. It is actually always running in the
background, making sure that the computer is going to run in the manner that
you would like and what you can get things to work the way that you would
like.
To start with some more of the particulars of the Mac system is the home
of this system or the desktop. This can be thought of as the physical desktop,
or a place where you are able to spread out the work that you are trying to do
while performing a task. For example, you could put up an image from the
internet on this desktop, make some modifications, and then drag it into an
email to send it to someone else. Just remember, while this desktop is going
to be a great place to do your work, it is not a long-term place to store your
files because it is going to get messy so you need to have files stored away in
folders and more to keep it organized and easy to work with.
The Dock
Next on the list is going to be the Dock. When you take a look at the
screen on your Mac computer, you are going to see what is known as the
Dock. This is basically a bar that is going to have all of the shortcuts that you
need for some of the applications that you use the most. If you do not see this
already there, you can move your cursor so that it goes over the bottom of the
screen, and then these are going to pop-up on their own. The icons that are on
this Dock are going to be shortcuts, and you are able to remove or add the
icons to this without having any effect on the applications themselves.
To add in a new application shortcut to this dock, you would just need
to work with the Launchpad, which is going to be a complete overview of the
applications that are available on your computer. In most cases, you will be
able to find this Launchpad in the left part of the Dock. You just need to click
on this and then view the applications available, before dragging an icon into
the dock to create a new shortcut if you would like.
The Menus
Now we are going to move on to the top of our screen where we are
going to be able to see a few menus. These menus are going to change
depending on the kind of application that you plan to use at that moment. If
there is anything that you want to do with the application that you are in at
that time, it is best to take a look for those actions in the menus.
We can also find some menu extras in all of this as well. We are able to
find these at the top of the screen that we are on. To the right of where we
were able to find the menus, we are going to see a few other symbols as well.
these little icons are going to be used to make some of the editing of our
settings easier on the Mac. Rather than having to go through and follow the
process to open up our System Preferences, we are able to change the settings
with the Menu extras.
If you are sharing the computer with others, then you will notice that
there are going to be a lot of different names that will show up when you
click on this as well. When you want to change out to a new user, you would
just need to click on their name and then log into their account. If there is a
password required, then you will need to focus on this as well and add it in.
The Spotlight
Another thing that we are able to spend some of our time on is the
Spotlight. If you look to the upper right corner of the screen that you are
working with, you will see that there is a smaller magnifying glass. This is
going to be the search function for this operating system, and it is going to be
the Spotlight.
The Dashboard
This operating system is also going to have a great thing that we are
able to work with that is known as the Dashboard. This is where we are able
to run some mini-applications that are known as widgets. This can allow us to
have a lot of potential freedom with the work that we want to do in this
operating system, and if you plan to have some work that requires widgets,
then this is the location where you are going to be able to find them.
1. The interface is simple but has a lot of power. This one is going to
offer us a really straightforward approach when it comes to
computing, and if you are used to working with an iPad or iPhone,
then you will find that the interface is going to be familiar. The
interface has been designed to be easy for anyone to use, making it
more appealing to those who want simplicity to get the work done.
Remember, however, that almost all of these operating systems are
not going to be intuitive by default. What is going to set this apart,
though, is that it is going to be upfront and clean overall?
2. It comes with fewer security issues and viruses overall: One of the
biggest advantages that we are going to see with this option is that
it comes with fewer security issues and viruses than other operating
systems. In the past, it was believed that Apple computers could
not get viruses, but that has since been seen as false. Even though
this operating system can deal with bugs and viruses on occasion,
the number of these incidents has gone down and are not as
prevalent as they are with other options. And it requires a lot less
maintenance to work with compared to Windows, so that is another
benefit to enjoy.
While there are going to be a lot of benefits that will come with working
on this operating system, there are a few reasons that people are going to
choose not to go with this option at all. For example, these mac computers
may work well, but they are going to be really expensive. If you are on a
budget, then this is not the best option for you to choose from. When it comes
to some of the upgrades in hardware that you would like to use, these systems
are going to be inflexible, and you will often have to just get another
expensive computer, in order to make this happen.
There is also a lack of game titles and advanced gaming experience when
you are working with one of these computers. For the avid gamer, working
with Windows is going to provide more options than what we will see when
focusing on the Mac operating system. There are a number of reasons for
this, but if you would like to spend some time gaming, then this is something
to be aware of. And the app ecosystem that we are going to see with this one
is still a bit lackluster and can turn some people away from it overall.
As we can see, there are a lot of great options that we are able to go with
when it is time to handle some of the choices in operating systems. Choosing
the right operating system can sometimes be a matter of preference, and
sometimes it is going to vary more on what kinds of codes you are hoping to
write, the coding language you choose to go with, and the end result that you
want to get. Picking out the right operating system from the beginning is
going to be so important to ensure that you are able to really able to get the
coding done that you would like.
Chapter 3: The C Languages
Now it is time for us to take a look at some of the programming that
we are able to do with the skills that we have. We are going to start out with
some of the C languages that are out there, including C, C++, and C#. Let’s
take a look at how we are able to work with these different languages, how
they are similar, and how they are a bit different along the way as well.
A Look at C
The main goal that we are going to see with the C language is that it
was supposed to be a language that is efficient but also would be able to form
around a community to have a fellowship. The community around this knew
that they needed to keep things running smoothly, and to do this, they
couldn’t just put information in a terminal on its own. But they needed to
have some communication after the coding as well. The result of this idea
was the C language. This is a structured language, and general-purpose, and
is known as a procedural oriented programming language. It hasn’t been
designed to work with a specific kind of application to start, but it does work
for business applications and scientific uses as well.
Getting the IDE
The first thing that we need to do before using C is setting up the IDE.
This is known as the Integrated Development Environment, and it is so
important because it will help us to write, link, edit, compile, and even run
the codes that we would like. The IDE is going to help us make sure that the
C language is going to work.
The best IDE for us to use is the Code Blocks IDE. This will come with
the features that are needed along the way. You won’t have to spend time
online or find another compiler with the right parts because this IDE is going
to have it al present right from the beginning. You can find this particular
IDE by visiting the website http://www.codeblocks.org.
To start this, we need to go into the Code Bocks IDE that we just added
to our computer, or you can use any other IDE that you would like. From
there, click on the New Button so that you can open up an Empty File. You
can then type in a code of your choice into the editor so that you can type in
the code and save it. A simple code that we want to work with, including:
main() {}
Now, when we get to this point, we need to save our file of the
source. This can easily be done when we click on the button Save. You can
either choose to get this one saved on the default for your computer or take a
moment to choose the folder where the code files should end u. Either way,
remember the location so you can find it later.
Another thing to consider is the name of the file you want to save. It
needs to be something easy so that you can remember it, and actually find it
at a later time if necessary. We will name this one as \u201cdummy.u201d so
that we can all be on the same page, but you can definitely pick something
that is a bit easier later.
While we are on the topic, you may notice when you try to execute
this part of the code that it is not going to the compiler for us. This is because
we are working on a dummy code, just to get some practice and not an actual
code. All of the codes that we spend time writing in C have to come with a
main function, along with something else, simply because this is where we
will see the execution of all our programs starts. We just need to add in the
main function we want to use inside those brackets, and we are good to go.
There are a few different types of loops that we are able to work with.
The first option we will focus on is the while loop. This one is going to allow
us to specify the condition that would get the loop to repeat itself. There
should also be some statements in place that are going to repeat themselves in
the code, and some condition that will get the loop to stop overall. If you do
not add in the last part, then the loop will get stuck, and you will not be able
to get it to stop at all.
To help us a little bit here, we are going to take a look at the while loop.
The code below is a good example of how we can work with this kind of
loop:
#include <stdio.h>
Int main()
{
Int x;
x = 1;
while(x <= 10)
{
Printf(“%d\n” ,x);
x++;
}
Return(0);
}
You will be able to use this syntax to help us create as many of the
while loops as we would need for our code. You do not have to stop at ten,
for example. You could have the code go up to 100 or some other number if
you would like. You just need to make sure that the code is set up to handle
this. Then, with the right condition in place, the while loop will continue on
its path until the condition is no longer met.
Do/While Loop
The second type of loop that we are able to handle in C is the do/while
loop. This is going to be similar to what we saw with the while loop, but it is
kind of upside down on this one. With the while loop, the code will check to
see whether the condition is true before even running the code. With the
do/while loop, we will execute the code, and check to see whether the
condition is still true before running it through again. If you are looking to get
the loop to run through at least one time, then the do/while loop is the best
option. A good example of the do/while loop in action will be:
#include <stdio.h>
Int main()
{
Char ch:
Ch = ‘A’;
Do
{
Putchar(ch);
Ch++;
}
While (ch != ‘z’);
Putchar(‘\n\);
Return(0);
}
You will notice that the do/while loop is going to start with line 9 with
the statement “do”. this one doesn’t have a condition because the statements
are going to be executed one right after the other. Then you can see that the
while condition is going to appear at your 14th line. The loop is going to rely
on the ch variable as the condition, and it is first initialized at line 7 before
being manipulated at line 12. Take a moment to build and then run this code
in your compiler.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
Int main()
{
Int column, r;
Srand((unsigned)time(NULL)); /*Seed Randomizer*/
Return(0);
}
The code that is listed above is going to be one that is about to output
ten randomly selected numbers. You can take some time to build this up and
then run the code to see that from the output, there is going to end up being a
row of ten values that have been randomly selected. The spacing between the
variables is going to be done when we use the ‘\t’ character that was put in at
line 14.
The Variables
In many of the languages that you are going to learn in this guidebook,
the variables are going to be important. Basically, this variable is going to be
a name that is given to the storage area that the program we create is able to
manipulate. Each variable in C is going to come with a specific type, which is
going to determine the layout and the size of the variable’s memory, the
range of values that we are allowing the program to store in that memory, and
the set of operations that we will let be applied to that variable.
You will find that the name of the variable is going to be composed of
digits, letters, and the underscore character. It has to begin with either an
underscore or a letter. And we must remember that in C, we need to worry
about case sensitivity, so be aware of the lowercase and uppercase letters that
you are working with as you name your variables.
There are a few types of variables that we are able to work within our
coding. Some of the most common types of variables that we can focus on
that will help with our C language will include:
2. Int: This is going to be the most natural size that we see for the
integer of our machine.
#include <stdio.h>
// Variable declaration:
extern int a, b;
extern int c;
extern float f;
int main () {
/* variable definition: */
int a, b;
int c;
float f;
/* actual initialization */
a = 10;
b = 20;
c = a + b;
printf("value of c : %d \n", c);
f = 70.0/3.0;
printf("value of f : %f \n", f);
return 0;
}
The C Functions
While functions are going to be important in all of the languages that
we explore, we are going to take some time to see how they work in the C
language. A function is going to be a group of statements that are going to
come together and perform a task. Each program in C is going to come with,
at a minimum, one function. This is going to be the main() function, and even
the most trivial and small programs in this language are going to add in a few
other functions to define.
You are able to divide your code up into separate functions. How you
are going to do that—is up to you, but you sensibly want to divide this up in a
manner that the function is able to perform the tasks that you would like.
Declaring a function is going to tell the compiler a lot of information,
including the name of the function, return type, and the parameters. And then,
the definition of a function is going to provide us with the actual body of the
function.
2. Function Name: This is going to be the name that you actually give
to the function. The function name and the parameter list are going
to come together to constitute the function signature as well.
A Look at C++
The net language that we need to take some time to look at is the C++
language. This one is going to have a ton of history behind it, and it is one of
the first coding languages out there. Because this language is one that has
been around for a long time, it is going to have a lot of programmers who like
to use it, which can be beneficial to you when you get started in this kind of
coding.
There are a lot of reasons why coders like to work with the C++ language,
and some of these are going to include:
2. I will work well with other languages. This is a good language that
can pair up with other languages. There are times in your coding
when you will need to pair together C++ with another language,
and this is easy to do.
3. Will work for most of the projects that you want to spend time on.
#include <iostream>
using namespace std;
int main ()
{
court << “Use This One!”;
return 0;
}
You have a few options available when it comes to writing this out.
You can choose to write this out in your compiler, which will be available in
your environment, or you can choose to write it out and save it to your
computer. The second option is sometimes nice because then you would have
the code saved and cold copy and paste it any time that you would need it in
your code.
Either way, you should carefully consider the type of text editor that
you want to work with. Most of them are going to be device-specific, so you
will need to look for the one that goes with your particular computer. Some
of the options that you can go with include Windows Notepad, vlm, vl, Brief,
and EMACS. If you would like to have an editor that is able to go on more
than one platform, then the vlm and vl options are the best ones.
This definition is also good for helping to specify the type of data that
you are interested in using. You will be able to type in a variable definition
like “type variable_list” and then choose the type of variable that you would
like to use and type it up in the same manner. These are going to tell the
compiler that it is time to create the type of variable that you would like to list
out. An example of the coding that you would use for this includes the
following:
#include <iostream>
using namespace std;
int. main ()
int j=10;
int k=5;
int l=j+k
{
cout <<l>> endl;
return 0
}
You should get the answer 15
It is also possible to go through and not only define, but also declare
the variables that are in the program, but it is something that we are able to
work with later on with some practice in C++. It is a good idea to get some
practice with doing this before we move on to the declaration process.
We also spend some time assigning a value to the variable that we want
to work with. If you just declare a variable, then all that you are doing is
reserving a bit of space on the computer memory, but nothing will be saved
there until you have been able to assign a value over to it. It is best to keep
this with one or two value to the variable, but you are able to do this in any
manner that you would like to make the code work.
These are going to be similar to the variables that are found in your
memory. But, you will find that they work in a more continuous manner than
what we can do with a variable. The lowest is going to be the first element,
and then the highest element will be the last one. You have a few options to
help us with this as well. For example, you are able to work with arrays by
choosing to initialize this one by one, or we can work with more of a
statement to make it work. A good option to help with this is the following:
#include <iostream>
using namespace std;
#include <iomanip>
using std::setw;
int main ()
{
int n[ 10 ]; //n is an array of ten integers
// initialize elements of array n to 0
for ( int i=0; I <10; i++)
{
n[i] =i+100; // set element at location I to i+ 100
}
cout << element << setw(13) << value<< endl:
//output each array element's value
for (int j=0; j<10; j++)
{
cout << setw(7)<< j << setw(13) <<n[j] << endl;
}
return 0
}
First, the conditional statements are going to be parts of code that will
ensure that the code is able to make decisions on its own, without the
programmer having to go through and think of all possibilities, and will help
the code know which decisions to make.
The Switch statements are going to help us to check out whether there
is going to be any kind of equality that is found in the variable by checking it
against the cases or the values that you outlined in the code that you are
doing. The variable that you are going to be checking with this statement is
going to be compared against a lot of other cases, depending on the code that
you are writing out. A good example of the syntax that is available for these
switch statements will include:
Switch(expression){
case constant-expression:
statement(s);
break; //optional
case constant-expression:
statement(s);
break; //optional
//you can add in as many of these case statements as you would like
Default: //Optional
statement(s);
}
When we spend time working with these switch statements, there are
going to be a few rules that we need to follow to get them to work inside of
our code. The first thing here is that the expression that we are using with this
statement has to be either an integral class or an enumerated class type. In
addition to all of this, it is also going to belong to a class that is going to have
a conversion function.
The good news with this is that when we work with C++, there will
not be a limit on how many of these cases statements that you can add in,
which can allow you to have a lot of freedom on the work that you are doing.
The important thing to focus on here is that there has to be a colon so that the
statement is going to work in the manner that we want.
How C# Is Different
C# can be classified as a general-purpose programming language that
is functional, declarative, generic, component-oriented, and object-oriented.
This language was developed by Microsoft in 2000 as part of the .NET
initiative and then was approved to meet with the international standard by
Ecma and ISO. It is a great language that is easy to organize, relies on the
ideas of OOP to keep it organized and easy to use, and more.
Like with the other two languages, we need to take a moment here
and look at how to write out code in C#. This will help us to see how the C#
language is similar to the other C languages, and how it is different. We are
going to work on a basic code that uses the C# language and a Windows
device. Notepad will be our text editor in this language (as long as you are
using Windows), so we will open that up and type in the code below:
class FirstProgram
{
static void Main()
{
Console.WriteLine(“Using C# is fun.”);
}
}
After you have issued this command, the compiler for C# will be able
to process this file and create the .exe file in the default directory. If you
saved this file on your desktop, for example, you can head there and should
see a new program named FirstProgram.exe, to know that you did this right.
You can run this by entering FirstProgram.ee into your command prompt,
and the output should be “Using C# is fun.”
There are a few types of data that we are able to work within this
language, including the following:
Ulong
Double
Long
Float
Uint
Int
Ushort
Sbyte
Short
Byte
Bool—when you use this type, the values that you are allowed to
store can only be two. The values are going to be false and true, so
it is good for conditional statements and logical expressions.
Decimal
Char—this is a data type that is only allowed to have one single
character. When you are writing the char value, you must include it
with single quotes such as writing out ‘t’ ‘b’ and so on.
Creating a Class
In C#, we are able to work with classes and objects. These help to
organize the language that we have and will make sure that nothing gets lost
in the process. We will take a look at the objects in a moment, but we need to
first set up a class that will hold onto these objects. That is the beauty of OOP
languages. They will create the classes, which are like little containers, that
hold the similar objects we have and keeps them all in one place for us to
easily access inside of our codes.
To start, when we want to create a class, we just need to use the class
keyword. Once we are able to start out with the code and work with that
keyword, it is time for us to indicate the identifier that you choose to use.
This is going to be done along with the methods and the variables that you
would like to use to get it all together and ensure that this works. We want to
make sure that this is simple, while also making sure that it actually happens,
so the main parts that we are going to see with a C# class will include the
following
1. Fields: These will be any of the variables that we are going to find
belonging to a particular type of data that we want to use.
Now that we know a bit more about these classes and how they work, it is
time to look at how we can actually create and work with one of these classes
along the way. We are going to look at the code below to help us get started
with this and to help us see how it is meant to work. For this class, we are
going to name it to book and then will add in the size and type properties to
make it work. The code that we need to use to make this particular class
includes:
Now, we need to take a look at this one a little bit. When we first look
it over, it looks complicated, but it helps us to see more of the syntax and
coding with this language, and makes it easier to see how classes are going to
be created. Looking at this one, we see the book class and it is going to have
two properties that are defined. The first one is that it will describe the book
size, and the second one is the book type. These properties are set up to hold
onto values inside of the fields that have the same name, and then the code
will help us to declare the two constructors for generating on this class.
Creating Objects
Remember how we have discussed that these C languages are object-
oriented programming languages? This means that we need to take a bit of
time looking at how to take these languages and create some of the objects
that are needed, as well. this will help us to really make sure that this will
work the way we want. We can then explore how to create objects, as well.
Once we have created the book class above, we are able to actually
create some objects and add them into that class. This will help us to get the
best results possible, and actually, make sure that some of the classes contain
items. The first thing we can do when creating this class is to create the
object. We will need to set it up so that we can make up the keywords that we
need.
The C# Constructors
The next thing on the list that we can work with is the constructors.
These are going to be a bit different than what we have discussed before, but
they are still important to our coding. They are going to be some methods that
we will see when they run as the program sets itself up to create a new object.
The idea that we see with these is that they are there to initialize the data of
that brand-new object as well.
You will not be able to get much value to show up when you use the
constructor method, and it is going to use the same name as we see with the
class that called it up, so you will need to spend some time matching up a few
names along the way to make it work. You will also get the choice of going
through and assigning the right parameters to this when the constructors
come out. The constructors will then be able to set up the parameters in a
manner similar to the other methods. You can even set up two or more
constructors in the same class if you would like, but if you do this, make sure
that the constructors are going to come from different data types.
class whileLoopDemo
{
public static void Main()
{
int x = 1;
class forLoopDemo
{
public static void Main()
{
// for loop begins when x=1
// and runs till x <=4
for (int x = 1; x <= 4; x++)
Console.WriteLine("GeeksforGeeks");
}
}
With this one, we are also working with what is known as an exit-
controlled loops. This will help us to go through and test out the condition,
but it is shown at the end of the body of the loop. What this means is that the
loop will execute itself at least once, and then check to see whether the
condition has been met. With the other loop, if the condition is met from the
beginning, then it will never go through the loop. This can sometimes make a
difference in the kinds of codes you are writing.
Another thing that we are going to notice with the C# language, that
may not show up in some of the other types of languages is the infinite loop.
These are going to the loops that will find that the test condition is not going
to evaluate anything as false at any time. This means that when we work with
them, they are going to continue on with executing the statement that you put
in until you use some kind of external force on them.
As we can imagine, there are not a lot of situations where you will
work with this, but it is still a good idea to know what it looks like. The code
we would see when working with an infinite loop in C# would include:
class infiniteLoop
{
public static void Main()
{
// The statement will be printed
// infinite times
for(;;)
Console.WriteLine("This is printed infinite times");
}
}
And finally, we also need to take a look at the do-while loop. This one
is going to be similar to the while loop, but it is going to be one of those exit-
controlled options, and the while loop is not. Some of the codings that we are
able to do with the d0-while loop that we are looking at here are below:
class dowhileloopDemo
{
public static void Main()
{
int x = 21;
do
{
// The line will be printed even
// If the condition is false
Console.WriteLine("GeeksforGeeks");
x++;
}
while (x < 20);
}
}
As we can see through this chapter, there are a lot of great things that
we can do when it is time to utilize the C languages, whether we are talking
about C, C++, or C#. They are going to share a lot of similarities to one
another, but there are times when we will need to go through and change up
the syntax and the method that we use on them. But when you need a high-
power program to get the work done, then these are definitely the languages
that you should consider.
Chapter 4: How to Code in Python
The next language that we are going to take a look at is the Python
language. When it comes to a multi-purpose language that is able to handle
all of the work that we want to do with coding, It was designed with the
beginner in mind, taking some of the codes that we focused on in the C
language and making them easier to work with.
There are a lot of different reasons why we will want to work with the
Python language. It is one of the best options to choose, and we are going to
take some time to look through a few of the different codes that come with
this language so you can see how simple it to code in Python. Let’s dive into
this language a bit more and see what we are able to do to make this work for
our needs.
The first benefit that we are going to see with this language is that it is
simple and easy to learn more about. This language was designed in order to
help beginners get started with coding. It may not be as complicated to work
with as some of the other options, but this makes it perfect even when
someone who has never been able to work with coding in the past will be
able to come in and get it all down in no time.
Another benefit that we are going to see with this language is that it
has a lot of power that comes with some of the codes that you try to work
with. Even though this is a language that is designed for beginners to use, you
will find that it is really going to come with a lot of power. This power can
help us to do anything from some basic coding, all the way to coding that is
more difficult, like what we see with deep learning and machine learning and
even some artificial intelligence as well.
And the final benefit that we are going to take some time to explore in
this chapter about Python is how it is able to work well with some other
coding languages as well. While the libraries that come with Python are
amazing and will have a lot of the features that you are looking for, and there
are plenty of libraries and extensions that we are able to work with that can
increase the functionality of Python, there will also be some times when this
is not going to line up, and Python needs a little extra push.
For example, Python can work really well with C# and C++ when it is time to
work with some of the different things of machine learning. This is just one
of the places where Python needs a little extra help. With the right tools, we
are able to write out the code in Python, add in those tools, and then ensure
that we are able to get it to work with the other language along the way.
One of the main components that are going to help drive this idea is
the classes. These classes are like little containers that we will use to hold
onto all of the objects that we create and what to make work inside of our
codes. When we are able to create some of these classes, code writing is
going to become so much easier, and we are going to get better results than
ever before.
Once we have chosen the name that we would like to give to the class,
it is time for us to go through and name the subclasses. This is the part that is
going to be inside of the parenthesis of the class that we show a bit later on.
Make sure that when you are near the end of this first line, after you create
the class, that you add in a semicolon to help get this all finished. While this
is something that we do not technically need and you can write the code
without it, most programmers are going to see this as the traditional and
proper way to write out code, so it is often best to add this in.
Writing out some of the classes that you want to have in Python is
going to sound a bit complicated at this point, but the good news is that there
are a few steps that we are able to utilize. We are able to go through with the
code below to get a good idea of how to set up one of these classes, and what
the process of creating our own class is going to look like in the process:
class Vehicle(object):
#constructor
def_init_(self, steering, wheels, clutch, breaks, gears):
self._steering = steering
self._wheels = wheels
self._clutch = clutch
self._breaks =breaks
self._gears = gears
#destructor
def_del_(self):
print(“This is destructor….”)
myGenericVehicle.Display_Vehicle()
This looks rather long, but we did go through and actually created the
class that we want to work with while adding in several objects to the mix to
make it work for our needs. With that in mind, though, we need to be able to
figure out how to access some of the objects that are in our chosen class. We
already went through and made the class and added some of the objects that
we want to work with. Now it is time for us to concentrate on some of the
steps that we need to use in order to actually access these to make them work
for our needs.
The best method to use, though there are a few options that we can
choose from is with the accessor method. The code that we can use to turn
this into something that we can work with includes:
class Cat(object)
itsAge = None
itsWeight = None
itsName = None
#set accessor function use to assign values to the fields or member vars
def setItsAge(self, itsAge):
self.itsAge = itsAge
def getItsName(self):
return self.itsName
objFrisky = Cat()
objFrisky.setItsAge(5)
objFrisky.setItsWeight(10)
objFrisky.setItsName(“Frisky”)
print(“Cats Name is:”, objFrisky.getItsname())
print(“Its age is:”, objFrisky.getItsAge())
print(“Its weight is:”, objFrisky.getItsName())
Variables are a great part of the code that we need to spend some time
on when we are in the Python language. The more that we are able to take a
look at them and learn ow this work, the better for us. These variables, to
start with, are just going to be small parts in the memory that we save back
and use to hold onto some of the different values that we would like to be
able to store.
We need to make sure that we go through and add value to the
variable, though. It is not going to do us all that much good if we go through
and do not add in any values here. This means that the variable is simply
going to hold onto a blank spot in the memory of our computer, and this is
not going to be all that efficient. But when we assign a value, and sometimes
we will assign more than one value to the same variable, it tells the computer
to place that value right in that location, and you can easily pull it up at a later
time if you choose.
The good news here is that we are able to assign any value that we
would like to a variable, as long as we use one simple symbol. And this is the
equal sign. As long as we have an equal sign between the value and the
variable, we are all set to go, and the computer will place that value where we
would like. It is that simple to work with variables in Python
The first loop that we can do in Python is the while loop. This loop is
going to be a good one to pick out when we know from the start how many
times we need the loop to go through its iterations. You would use this when
you want to create a code that can count to ten, for example. Make sure with
this one that there is a condition at the end that will tell the code when to
stop; otherwise, you are going to get stuck in a loop and will not be able to
get the computer to unfreeze without stopping the whole program. The code
that you are able to use for the while loop includes:
counter = 1
while(counter <= 3):
principal = int(input(“Enter the principal amount:”))
numberofyeras = int(input(“Enter the number of years:”))
rateofinterest = float(input(“Enter the rate of interest:”))
simpleinterest = principal * numberofyears * rateofinterest/100
print(“Simple interest = %.2f” %simpleinterest)
#increase the counter by 1
counter = counter + 1
print(“You have calculated simple interest for 3 time!”)
Then we are able to move on to the loop n Python. This one is a bit
different in how it works, and it is often seen as the more traditional form of
making loops in Python. If you are not certain which method to work with,
and if you are worried about learning all of these loops, then you need to
focus on the for a loop.
With these for loops, we are not going to allow the user to go through
and provide any of the information that the code needs for the loop to start.
Rather, with this loop, Python is going to be set up so that it can go through
the iterations in any order that you pick them out and place them in the code.
The user will have no need for adding in the input because the loop will just
go through the iteration that is set up at the time. A good example of how we
are able to work with the for loop includes
Write this code into your compiler and then execute it. The for loop is
going to make sure that all the words in the line above it are shown up on the
screen, exactly how you wrote them out. If you want them in a different
order, you need to do that as you work on the code, not later on. You can add
in any words or other information that you want to show up in this kind of
loop, just make sure that you have it in the right order from the beginning.
The final type of loop that we are able to take a look at is known as
the nested loop. This is where we are able to combine together two of the
loops that we have from before. These will both start together and will not
complete until both of them are done. This can be used in situations like
creating our own multiplication table. Some of the codings that we can use in
order to help us create some of these nested loops will include:
When you got the output of this program, it is going to look similar to
this:
1*1 = 1
1*2 = 2
1*3 = 3
1*4 = 4
2*1 =2
2*2 = 4
And so on until you end up with 10*10 = 100 as your final spot in the
sequence
Any time you need to get one loop to run inside another loop, the
nested loop will be able to help you get this done. You can combine together
the for loop, the while loop, or each combination based on what you want to
get done inside the code. But it definitely shows you how much time and
space inside the code that these loops can save. The multiplication table
above only took up four lines to write out, and you got a huge table. Think of
how long this would take if you had to write out each part of the table!
The for loop, the nested loop, and the while loop are all going to be
common loop types that we are able to work with as a beginner and can help
us to clean up some of the codings that we are doing with Python in the first
place. Knowing how these works and how we are able to put them together is
going to make a world of difference in some of the coding that we can do,
can clean things up, and is definitely a benefit when it comes to doing some
of this work in Python.
The nice thing about these conditional statements is that they are set
up to make sure that the code is able to make some decisions, on its own,
based on the conditions that you set from the beginning. This makes the
program more interactive and can help it respond to the user, even when you
are not able to make predictions on everything that will happen.
Now, with this one, if the user puts their age as under or equal to 18,
they are going to get the message that is in the parentheses below. But what
happens when the user comes in and is 42, or some other age that is higher
than 18? The if a statement is not going to be able to handle this. That is why
we can move on to the if else statement.
We can add the if-else statement to the code that we did above. This
helps us to have something happen to our program, whether the user says that
their age is over or under 18. The code that we are able to use to make this
happen in our Python code includes:
as we can already see here, this is a much better option to work with. It can
handle any answer that the user has, and will provide them with some kind of
information no matter what they use for the program.
We can take this to the next level, though, if we would like, and this
would include the elif statements. These are kind of similar to what we will
see with the if else statement, but we will present the answers to the user.
They will receive a type of menu, similar to what we will find in games, and
then they can choose from one of those options. A good example of how
these elif statements are going to work will be below:
This helps us to maintain some order in the coding that we do and will
keep things organized, allows us to reuse some of the features that we want,
and prevents us from having to rewrite the same parts of the code over and
over again. This will make it easier for us to keep the code organized and
ready to work with.
To help you to make more sense out of these inheritances, and how
they are all going to work, and how they are so important to the code while
keeping it clean and organized, all while saving time, we need to look at an
example of how an inheritance will work in Python below:
#Example of inheritance
#base class
class Student(object):
def__init__(self, name, rollno):
self.name = name
self.rollno = rollno
#Graduate class inherits or derived from Student class
class GraduateStudent(Student):
def__init__(self, name, rollno, graduate):
Student__init__(self, name, rollno)
self.graduate = graduate
def DisplayGraduateStudent(self):
print”Student Name:”, self.name)
print(“Student Rollno:”, self.rollno)
print(“Study Group:”, self.graduate)
def DisplayPostGraduateStudent(self):
print(“Student Name:”, self.name)
print(“Student Rollno:”, self.rollno)
print(“Study Group:”, self.postgrad)
When you type this into your interpreter, you are going to get the results:
This may look like a lot of code to work with, but in reality, it is
taking care of a lot of different parts at once. We are writing the original part
of the code that we want to use, and then moving it down and making some
modifications, all while still getting some new things added or taken away
from it so that the code behaves in the manner that you would like.
There are a lot of things that we are able to use this SQL language to
help us out with. For example, it is meant to help us get a lot of the work
done that we need with the database. It will help us to execute queries on our
database, get data insert some new records or update the records that are
already there, delete some records if we no longer need them, create a new
database or some of the tables that are inside of the database, store any of the
procedures that we want in that database, create some new views, and even
set some of the permissions that we need in relations to the database.
As we can see, there are a ton of things that we are going to see
happen when it comes to working with SQL programming. We are able to
use it to help us with anything that relates back to the database that we are
working with, and this is part of what makes it so powerful.
There are numerous advantages that we are going to see when it comes to
working with the SQL language, and it is important for us to recognize some
of these and learn how we are able to make them work for our needs. Some
of the main advantages that we are going to see with this language include:
1. You don’t need to work with coding: It is possible to work with the
standard SQL and get through the database system, doing all of the
tasks that you want, without having to use much coding. In fact,
most of the things that you want to do with SQL will just require a
few lines or less of code in this language.
2. The standards are well defined: The standards that are followed in
SQL have been around for a long time, and this makes them more
reliable and easier to work with. There are none of these standards
found in databases that do not rely on SQL.
5. Multiple views of the data: With the help of this language, the
users are able to make different views of the database structures
and databases for the different users.
These are just a few of the advantages that you are able to see when it is
time to work with this language overall. And it will not take long working
with it, along with your own database, to learn how well this can help us out
with getting work done. Whether you are creating some of your own tables,
changing up the database, or doing some of the other options allowed here,
you will find that SQL is going to be a great coding language to focus on.
2. AND: This one is going to be one of the operators that we can use
that is set up to combine together two conditions. Both of the
conditions have to be true for the row before it is added in with the
result set.
15. OR: This is an operator in SQL that is going to filter out the
results that we get, and then we will only include the rows where
either condition is seen to be true.
16. ORDER BY: This is going to be a clause that will indicate what
you want to sort the result set by a particular column. You can
choose to do this numerically or alphabetically based on the
information that we are working with.
20. SUM: This is another function that we are able to work with
that is going to take as the argument the name of our columns, and
then will return the sum of each and every value that is found in
that particular column along the way.
22. WHERE: This is a clause that we can use that will indicate that
you would like to filter the result set, only including the rows where
the conditions that you have set are going to be true.
23. WITH: This is a clause that is going to help us store the results
of our query in a table that is temporary and using an alias. You are
also able to define more than one table using a comma and one
instance with this keyword. The WITH clause is often going to be
known as a CTE, or the common table expression and the subquery
factoring.
How to Create a Table
The next thing that we are going to take a look at is how to actually
take some of the commands that we did above and putting them to good use.
And the first option is taking a look at the CREATE TABLE statement. At
some point, you are going to have a database and will want to be able to
create at least one table, though sometimes many tables, inside of that
database. These tables are able to hold onto some of the important
information that you want to deal with when it comes to working in SQL, and
this is why they are important to work with.
To make one of your own tables, we will simply want to use the
statement of CREATE TABLE to make it happen. The basic syntax that we
are going to use for this one will be below:
Keep in mind here that there are actually quite a few different types of
data that we are able to use. We will see a lot of the same types of data that
showed up in the other coding languages. We have to choose which one is the
most important for our needs as well.
From there, we are able to take this a bit further and actually create
one of our own tables. We are going to work on creating a table that we will
label as “Persons’ and then we are going to add in some of the identifying
information about these people as well. the code that we would be able to use
to make this one happen includes:
The column that we are working with for the PersonID is going to be
a type int, and then it is going to hold onto the integer. For example, on the
other hand, we do not want numbers in some of the other columns that we
created above. So this means that the other columns are able to hold onto
characters or are type varchar, and then we set the maximum length for these
all to be at 255 characters, which should be plenty to hold onto some of the
information that we want about names and addresses.
There is one final thing that we are going to take a look at doing while
we are on the topic of creating tables. This one is where we are going to
create a table with the help of another table that is already in existence. This
means that a copy of one of our other tables can be used to help create a new
one, using the same command as before.
The new table that we are trying to make is going to end up with the
same definitions of columns. And we can choose to work with all of the
columns in this manner or some of the specific columns as well. if you want
to create this new table with the help of the table we already have, then we
will find that the new table is going to be filled up with all of the same
existing values that we are going to find from that original table as well. the
syntax that we are able to find with this one will include:
We can take this a bit further and look at an example of how this can
all be set up for our needs. The following option is going to help us to create
a brand-new table, which we are going to call “TestTables” and it is going to
be a copy of the table that is known as Customers. The code that we can use
to make this happen will include:
The first thing that we can do is make sure that we are adding in a
new column to one of the tables that we have. We are going to want to use
two commands here. We will start out with the ALTER TABLE and then tell
the compiler that we want to ADD to it. The syntax that we are able to work
with here will be below:
Doing a Query
The final thing that we need to take a look at when it is time to work
with SQL is that we want to be able to do a query. If we have a database that
is pretty large, it is important that we are able to go through and find the
information that we would like. You do not want to go through this and try to
manually figure out what is going on or how you can use it. You want to be
able to do a quick search, and the queries in SQL, or the SELECT statement,
will make sure that this is able to happen.
The next step is to get started with some of the programmings that we
are able to work with. There are a lot of great coding languages that are
available out there for us to work with. But some of the best options to work
with, the ones that are going to really help us to handle most of the coding
that we want to accomplish, including C, Python, and SQL. This guidebook
is going to take some time to look through these languages, along with
computer programming in general, to help us to really learn more about
programming and how to get started as a complete beginner.
The next few sections we looked at took some time to explore what is
going on with some of the most common languages out there. We explored
some about the C languages, which include the C, C#, and C++ language,
how they are similar, and how each one is different from one another. We
then moved on to looking at the Python language and how this is often the
language that is preferred by many new programmers who have never had a
chance to work with coding in the past. And finally, we took a look at some
of the work that we are able to do with the SQL language and how this can
come into play when we want to handle our databases and make them as
strong as possible.
There are so many cool things that you can do when it is time to focus
on computer programming, and with some of the tips and tricks that we
discussed I this guidebook, you will be able to learn these programming
languages in just a few days, and sometimes even in just a day, rather than
wasting time and spending years on the basics. When you are ready to learn
more about computer programming and some of the most common coding
languages, make sure to check out this guidebook to help you get started.
Finally, if you found this book useful in any way, a review on Amazon is
always appreciated!
Computer Programming:
PYTHON
A step-by-step guide to learn the basic concepts of
Python programming language with practical
exercises
Tony Chan
Introduction
You may choose one or more areas you're interested in and willing to follow.
You will focus your learning in your field of interest and ultimately will be
able to build projects in those areas.
● Learning the basic syntax
Sadly, you can not skip this specific step while learning Python. You must
learn the very basics of Python syntax before plunging more profound into
your area of interest. We know that, on this, you want to spend as little time
as possible, since it's not inspiring or motivating. In this book, we are going
to help you learn some basics of Python syntax.
● Making Projects
Once you have learned the basic syntax, you can start making your own
designs. Developing your own Projects is a great way to learn because it let
you transfer your knowledge into something productive. You should
remember that it will be difficult to gain more knowledge unless you apply
your own. Projects will improve your skills help you to understand and learn
new things, and help you build a portfolio for potential employers to present.
But, at this stage, very freeform projects will be difficult. You are going to
get stuck a lot, and have to return to the paperwork and reading. Due to this,
developing more formal projects is usually better before you feel comfortable
enough to construct projects entirely under your own. Most of the tutorial
websites or books provide organized projects so that you may learn from
them. After editing these projects a bit, it allows you to create things that are
interesting in the area you care about while stopping you from getting lost.
You might be involved in Python because you'd like to make a game, or work
in technology, or do Anything else. So, we are going to look at the future of
Python at the end of this book.
● Work on Projects on your own
It is the time to work on your very own projects after you've completed some
organized projects offered by different tutorial websites, as mentioned above.
It's hard to figure out how much you really learned on your journey to learn
and understand Python before you step out and try to develop a project on
your own. No one is perfect, so we know that you're still going to consult
resources and learn new concepts of Python programming as your work
continues but, at this time, you're going to work on Anything you want to
work upon.
As mentioned in the earlier point, you should be comfortable with debugging
errors and problems within your program before you plunge into developing
your own Python projects. But, here are some helpful resources that you may
consult while having an issue in your project.
● Stack Overflow
Stack Overflow is a forum where you may question about your issue and can
get a helpful answer from someone else. Most people discuss programming
related issues on Stack Overflow.
Moving forward, Python-specific questions can be answered here as there are
thousands of Python developers that visit it daily. If you need to, you can
always ask your question, but usually, a search on Stack Overflow will show
that someone has already asked about the issue you're facing and got a nice
answer.
● Google
Second, on the list is Google. We have to believe that Google is the
programmer's most widely used tool and search engine. You may find
Google quite helpful when attempting to debug or fix a programming error.
Once all the above-mentioned phases have been completed, you should keep
increasing the complexity and variety of your projects in Python
programming. If you're entirely comfortable with what you're designing, it
means it's time for you to try something more complex and quite more
complicated. You may consider starting a new and tougher project or adding
some complexity to your recent project, or maybe, you may bring your
project to a completely different kind of challenge. For this! You have to
remember that practice makes a man perfect!
The following are some suggestions to raise the complexity of your projects
to make sure you're really making progress in learning Python.
● You may try to teach a noob how did you manage to build your
project. Nothing better can help you to learn a subject as to teach
it!
● You should think about the processes that may increase the
capability of your project.
● You may consider working on the efficiency of your project.
● You may think of ways to make your project more user-friendly.
● You may consider ways to publicize your project.
Let's say you've saved your written program Hello to the World of Python
Programming project as a Python file, i.e., ".py file". Now, on your device,
you should look out for a ".py" extension file. Just say that you've saved your
project as "Hello to the Python.py", here's how your code will work in the
scripting mode of Python.
At first, the project file that you've written and saved must be functional and
executable. Typically, programmers do this preferably by using the
command:
$ chmod +x test.py
Now, if your file is functioning and executable, you may run your program in
Python's scripting mode.
Once this command is executed, you'll see "Hello to the world of Python
Programming!" written on your Computer Terminal or console. One "Hello,
to the world of Python programming" is executed, you've learned your first
Python Syntax.
● Keywords and Identifiers In Python
In Python Programming, there is a total number of thirty-one keywords and
five significant identifiers.
Identifiers and keywords are something that you'll become used to
effortlessly while you focus on your Python programming skills.
● Python Identifiers
A Python Identifier is typically a function, a module, a variable, a class, or
something else. In Python programming, you assign an object a name, and
this is known as an identifier. Typically, a valid identifier begins with either
an uppercase letter(A-Z), a lowercase letter (a-z), or an underscore (_).
Usually, these are followed by underscores, zero, letters, or numbers (ranging
from 0 to 9).
In Python programming, there are five basic types of identifiers:
● Functions
● Modules
● Class
● Variables
● Other Objects
Moving forward, we should take a look at the keywords that are available in
Python's syntax.
● Basics Python Syntax Keywords
To see all thirty-one keywords in Python, you have to open your IDE and
type the following command:
Output:
When you’ll enter these commands, your IDE will print this:
These mentioned keywords can change with every new version of Python.
Now, there are a few more things that you should keep in mind while
working with Python as a programming language
● Keywords are fixed, and we can not use them as our Identifiers.
● Keywords in Python are case sensitive. Typically, we call these
keywords as reserved words.
● Python Statements
The very next things you should keep in mind are Lines and Indentation
before we further move with the basic concepts of Python Syntax.
In Python, indentation is the primary support in organizing code blocks or
modules. Moreover, it's rigidly enforced, and it makes your Python code
readable, scannable, and reviewable.
We have to remember that under each situation, the space that goes with the
indentation varies. To understand this, we have to observe the following
code:
In the following code, you have to note that how the "for statement" has one
space, i.e., indentation and "if statement" has two spaces.
In Python, when you finish a line using a semicolon, you terminate a
sentence.
;
Moving forward, in Python, you may also declare multiple statements
effectively in a single line. For example:
person="Faheel Nasir";age=25;location="Lahore"
● Command Line Arguments
We basically used a command-line argument in "Hello to the Python.py" and
in the interactive script. So, it is the easiest manner to introduce you to the
command line arguments. These are an essential part of the fundamentals of
Python programming syntax, which you should learn about.
● How to create a Virtual Environment
Virtual Environments will be one of those things you're going to create for
every new project. In Python, you may also work on new projects without
having to create new virtual environments. However, doing that would mean
that you will end up in a situation where
● You can not improve/optimize dependencies. For example, you
may not upgrade the default version of Python (from 2.7 to 3.8).
To develop a new virtual environment, you should go to your Terminal and
type the following command
$virtualenv newevironment
In this command, the name of the virtual environment we just developed is
"newenvironment". Now, type the following command to start your new
environment
source newenvironment
● Taking User Input
You could find two common types of Python syntax which may request the
user input
● raw_input
● input ()
Each of them prompts a user to enter their inputs.
● raw_input ()
In Python 3, this is no longer true or valid. Instead, input() is the new input
form.
● Input()
To understand this concept, we have to look at the following example:
After entering this, your IDE will allow you to enter your imaginary friend's
name.
Special Features:
● Effective debugging.
● It provides an efficient code route.
● Highlights errors significantly.
● The SPYDER IDE
The SPYDER IDE is the best IDE for the developers of data science. It is an
open-source IDE. The full form of SPYDER is "Scientific Python
Development Environment." SPYDER is compatible with Windows OS,
MAC OS X, and LINUX OS oriented machines. SPYDER usually includes
the Anaconda bundle director dispersion, so that you may rely upon your
own.
The fascinating fact about SPYDER is that it is used to intend the interest
groups of information researchers using Python. SPYDER coordinates well
with standard Python information science libraries like Matplotlib, SciPy, and
NumPy.
SPYDER has a vast number of the basic IDE functions that you may
imagine. For instance, SPYDER is a Python code manager having a durable
feature for language structure. Moreover, it INCLUDES fulfillment for
Python's code, and it's even an IDP, i.e., Incorporated Documentation
Program.
Moving forward, a different element that you may not see in other Python
IDEs is that SPYDER contains a "variable voyager". It enables you to display
information, while utilizing a table-based design, inside your IDE.
Special Features:
● IPython Integrated
● Proper quality Syntax
● The PYDEV IDE
The PYDEV IDE is one of the highly demanded python IDEs in the world.
As far as the Python developers are concerned, they prefer PYDEV for so
many reasons. PYDEV has a feature that incorporates "django" combination,
shrewd indents, programmed code fruition and square indents, and many
more.
PYDEV is accessible at Windows OS, MAC OS X, and Linux OS oriented
machines. We may consider PYDEV as the accepted open-source IDE for
Java-based advancement as well. It includes a commercial center for
additional and expansion items. This feature makes PYDEV helpful for a
broad scope of improvements and exercises.
Special Features:
● Contain PyLint combination, remote debugger, Unit test joining.
● Code inspection and verification.
● The Atom IDE
Atom IDE is the most popular IDE for Python, developed by GitHub. It is a
cross-platform and open-source IDE.
In Atom IDE, the initial and instructional exercises brief you all about the
functions of the concerned IDE, step-by-step. A coordinated advancement
tech enables you to start a highly integrated working between two different
platforms. That is why Atom IDE is highly recommended for cross-platform
program management and effective and efficient editing for your Python code
while executing the live programs.
Atom IE has a draw-back as well. The developers, using Atom IDE, consider
it the least secure tool. But, it is considered as the best tool for amateurs and
beginners. However, apart from its pros and cons, Atom IDE is one of the
best tools for information science that enables you to work with high-level
computer programming languages.
Special Features:
● It has a module "Markdown Preview Plus".
● It shows up the results in runtime windows.
● The Wing IDE
Firstly, Wing IDE is open-source and free. It has a few highlights in it that
may allow syntax structure featuring auto-fulfillment, investigating, and
indents.
It has a paid version as well, named as Wing Pro. The advantage of using
Wing Pro is that it provides debugging, highlights, and many more to your
Python code.
Special Features:
● It supports remote advancement, test-driven improvement
alongside the unit test.
● It's customizable, and it can have expansions too.
● Jupyter Notebook IDE
Jupyter IDE is an IDE that is created for the server-client structure. It enables
you to develop and control notepad reports for your Python-based program.
Jupyter Notebook was released for IPython in October 2014. It is a web
application that depends upon the server-client structure, and it also enables
you to develop, customize, and control the reports that are made on Scratch
Pad or Notepad.
However, Jupyter Notebook proves to be a fundamental part of every Python
information researcher's toolbox. It is outstanding for the development of
prototypes and is also useful for imparting scratchpad to a representable
form.
Special Features:
● In this IDE, your code can be generated and changed easily.
● Jupyter notebooks include a feature for supporting markdowns.
● This IDE is best for beginners in the field of data science.
● Thonny IDE
If you are a beginner in Python programming and you want to learn and
master the Python programming language, Thonny IDE is one of the best
ways of doing it. Thonny IDE is the most used IDE by the beginners of
Python and is considered as easiest to understand IDE. It possesses a very
common and simple development environment for the Python data science
community.
Special Features:
● In this IDE, debugging is really easy and straightforward.
● Thonny IDE contains the feature of auto code finishing along with
debugging blunders.
● Microsoft Visual Studio IDE
Microsoft Visual Studio IDE is the best suitable IDE for investigating and
improvising web-based activities. This IDE is an open-source code generator,
and it has its market. Furthermore, this IDE is created by Microsoft.
Special Features:
● It IDE allows you to code in Python in the visual studio
environment, which is a very unique feature of this IDE.
● This IDE is available in both forms; paid form as well as free.
● Why IDEs and Code Editors!
The question arises! Why do you need a code editorial manager or an IDE!
Generally! By using a code editorial manager or an IDE, you may give
directions to a terminal so that you may be able to execute your code and
projects
We have to mention that adopting the same process for huge codes and
lengthy programming tasks can disappoint you. Mostly, it will disappoint you
if you do not know how to use direction line translator applications.
Moving forward, using an IDE can make programming or coding more
straightforward, easy to understand, and a fun thing. IDEs are basically
coding devices or instruments that allow you to write, test, execute,
troubleshoot, debug, compile, and run your code. IDEs and code editor
applications are the best approach for beginners for speedy work. These IDEs
can provide code auto-finishing and may allow you to understand the
sentence and syntax structure.
Key Benefits:
● It is free of cost, and it provides a totally movable programming
environment.
● It provides automatic expansion of segments that are required for
the record structure.
● It supports multiple Operating Systems having a 24-bit color
system.
Example - 1:
Open the Python console or IDE and write the command to declare variables.
>>> n=v=w=69
>>> print
>>> print (n, v, w)
Output:
When you type the command to print the value of variables, the output will
be something like this.
>>> 69, 69, 69
>>>
Example – 2:
>>> n, v, w = 69, 74, 36
>>> print
>>> print (n)
>>> print (v)
>>> print (w)
Output:
For output,
When you will type your command
>>> print (n)
Your console will print "69"
When you will type your command
>>> print (v)
Your console will print "74"
When you will type your command
>>> print (w)
Your console will print "36"
We are going to discuss some of the above mentioned operators in this part.
● Arithmetic Operators
Arithmetic operators are used to perform particular arithmetic operations to
get the desired results. In this case, two operands are taken, and between
them, activity through an operator is performed, resulting in some desired,
specific, and absolute value.
Here are some of the critical and useful arithmetic operators, which are
commonly used in Python.
● Addition "+"
● Subtraction "-"
● Division "/"
● Multiplication "*"
● Remainder "%"
A detailed description of these operators:
● Addition Operator "+"
This operator is used to perform addition or sum function between two
operands.
Example:
>>> n, v = 25, 69
>>> n + v
Your console will print “94”, in this case.
● Subtraction Operator "+"
This operator is used to take the first operand and subtracts the second
operand from the first one.
Example:
>>> n, v = 69, 25
>>> n - v
Your console will print “44”, in this case.
● Division Operator "/"
This operand takes the second operand and divides the first operand on the
second operand, and gives quotient, as your output.
Example:
>>> n, v = 4, 2
>>> n / v
Your console will print “2.0”, in this case.
● Multiplication Operator "*"
As explained earlier, this operator performs the multiplication operation
between the first operand and the second.
Example:
>>> n, v = 4, 2
>>> n * v
Your console will print “8”, in this case.
● Remainder Operator "%"
This operator is responsible for the operation of division, and it gets the
remainder as your output.
Example:
>>> n, v = 4, 2
>>> n % v
Your console will print “0”, in this case.
● Comparison operator in Python
Comparison operators, in Python, are used to compare two operands and
returns a Boolean type, i.e., TRUE or FALSE, respectively.
● ==
True: This operator is used if and only if the values are logically equal and
true.
● !=
True: This operator is used when the values are true but unequal.
● <=
True: This operator is used when the first operand is smaller than or equal to
the second operand.
● >=
True: This operator is used when your first operand is greater than or equal to
the second operand.
● <>
True: This operator is used if and only if the values are not equal.
● >
True: This operator is used when your first operand is greater than the second
operand.
● <
True: This operator is used when your first operand is less than the second
one.
● Assignment operators in Python
In Python, we use assignment operators to assign the value to the left
operand, of the right-side expression.
● =
Frequently, this operator is used to assign the value of the right expression to
the left operand.
● +=
This operator is used to build the estimation of the left operand by the
estimation of the correct operand and appoint the altered an incentive back to
the left operand.
Example:
>>> n = 2, v = 4
>>> n += v
This will be equivalent to
>>> n = n + v
>>> print (n)
And your console may print the value if n as "6".
● -=
As far as this operator is concerned, it diminishes the estimation of the left
operand by the estimation of the correct operand and dole out the changed an
incentive back to the left operand.
Example:
>>> n, v = 4, 2
>>> n -= v
This will be equivalent to
n=n-v
>>>print (n)
And your console may print the value if n as "2".
● *=
It increases the estimation of the left operand by the estimation of the correct
operand and appoint the altered an incentive back to the left operand.
Example:
>>> n, v = 4 , 2
>>> a * = b
This will be equivalent to
n=n*v
>>> print (n)
And your console may print the value if n as "8".
● %=
This operator is responsible for Divides the estimation of the left operand by
that of the correct operand and appoint the update back to the left operand.
Example:
>>> n, v = 4 , 2
>>> a % = b
This will be equivalent to
n=n%v
>>> print (n)
And your console may print the value if n as “0”.
● Logical Operators in Python
As far as our real lives are concerned, sometimes, we have to make tough
choices based upon logical data, i.e., true or false. For example, let us say if
someone calls you and asks you, "Are you at home?" You would have two
choices, "Yes! I am home" or "No! I am not." This would lie under 0 (false)
and 1 (true), in programming. This is known as logical data.
In Python, Logical operators are used to evaluate the expressions to obtain
some specific decisions. These operators are highly helpful to write any logic
reasonably. Here is the list of logical operators with a brief description to
build a better understanding with these operators in Python.
Logical Operator Description
● And Operator
If an expression "n" is true, and another expression "m" is true as well, then
the result will be true. In any other case, the result will be false.
This table may help you to understand "and operator", in a better way.
n v n and v
● Or Operator
This will result in false, if and only if both operands are false. Consider an
expression "n" is true, and another expression "v" is false, then the result will
be true.
This table may help you to understand "and operator", in a better way.
n m n or m
Example:
>>> n = 69
>>> v = "Hi Python"
>>> w = 17.5
>>> print ( type (n));
>>> print ( type (v));
>>> print ( type (w));
Output:
When you will type the command
>>> print ( type (n));
Your console will print
<type 'int'>
When you will type the command
>>> print ( type (v));
Your console will print
<type 'str'>
Example:
>>> n = 69
>>> v = 96
In the above-mentioned example, n and v are the numeric objects
Four different types of numeric data are supported by the Python
● Integer (int)
Int signs integers, such as 69, 96, 22, etc.
● Long Integers (long)
Long integers are used for a relatively higher range of integer values, such as
-0x19292L, 908800L, etc.
● Float (float)
In Python, float is used to store floating-point values, such as 1.9, 69.1902,
262.2, etc.
● Complex
This type, in Python, supports complex numbers, such as 12.14j, 2.0 + 12.3j,
etc.
Moving forward, Python allows using a lower-case "l" to be used with the
long integers. But you must ensure that always an upper-case "L" is used for
clarity and basic understanding.
Moreover, a complex number always consists of an ordered pair, such as n +
iv where n and v denote the real and imaginary parts, respectively.
● String
In Python, we may describe string as a sequence of characters that are
represented in the quotation marks. Moreover, single, double, or triple quotes
can be used to define a string.
String handling is a simple, understandable, and very clear task since there
are many in-built functions and operators that are provided by Python to
execute this task. For string handling in Python, the operator "+" is used to
concatenate two strings as the operation
"Hi" +" Mr Faheel Nasir"
Returns,
"Hi Mr Faheel Nasir".
Furthermore, the operator "*" is commonly known as a repetition operator as
the operation
"Mirror" * 2
Returns,
"Mirror Mirror"
You may understand string handling in Python, with the help of the following
example:
Example:
>>> string1 = "Hi Mr. Faheel Nasir"
>>> string2 = “How are you”
>>> print (string1 [0:2]) #printing first two character using slice operator
>>> print (string1 [4]) #printing 4th character of the string
>>> print (string1 * 2) #printing the string twice
>>> print (string1 + string2) #printing the concatenation of string1 and
string2
Output:
When you write the first command and press enter, i.e.
print (string1 [0:2])
Your console will print the first two characters of your string using a slice
operator. So, in this case, your console will print, "Hi".
When you write the second command, i.e.
print (string1 [4])
Your console will print the fourth character of your string. So, in this case,
your console will print, "r".
When you write the third command and press enter, i.e.
print (string1 * 2)
Your console will print your first string twice. So, in this case, your console
will print, "Hi Mr. Faheel Nasir Hi Mr. Faheel Nasir".
When you write the fourth command and press enter, i.e.
print (string1 + string2)
Your console will print the concatenation of string1 and string2. So, in this
case, your console will print, "Hi Mr. Faheel Nasir How are you".
● String Operators
Addition Operator "+":
In Python, the Addition operator "+" is used to join the strings in a program.
Multiplication Operator "*":
In Python, the Multiplication operator with the symbol "*" is used for the
generation of multiple copies of the same string to perform and to call a
function.
Slice Operator "[ ]":
In Python, the slice operator is used to make a sub-string available, out of a
specified string.
Range Slice Operator "[:]":
In Python, we may use the range slice operator to perform a function and to
call or get characters.
In Operator "In":
This is a membership operator. It returns a value against the presence of a
specific substring in the main string.
Remainder Operator "%":
The remainder operator, in Python, is used to perform string formatting.
● Lists
In Python, we use lists as we use arrays in C or C++. But, the list may contain
data of various types. The stored items in a list are separated by a comma ","
and enclosed within square brackets "[ ]"
Slice operators "[:]" may be used to access the list's elements. The addition or
concatenation operator "+" and repetition or multiplication operator "*" work
with the list in the same way as they work with the strings.
Example:
>>> l = [1.5, "Hello", "Python", 7]
>>> print (l [3 :]);
>>> print (l [0:2]);
>>> print (l);
>>> print (l + l);
>>> print (l * 3);
Output:
When you write the first command and press enter, i.e.
print (l [3 :]);
Your console will print will print, “[7]”.
When you write the second command and press enter, i.e.
print (l [0:2]);
Your console will print, "[1.5, 'Hello']".
When you write the third command and press enter, i.e.
print (l);
Your console will print, "[1.5, 'Hello', 'Python', 7]".
When you write the fourth command and press enter, i.e.
print (l + l);
Your console will print, “[1.5, 'Hello', 'Python', 7, 1.5, 'Hello', 'Python', 7]”
When you write the fifth command and press enter, i.e.
print (l * 3);
Your console will print will print, “[1.5, 'Hello', 'Python', 7, 1.5, 'Hello',
'Python', 7, 1.5, 'Hello', 'Python', 7]”
Python List Built-in functions Description:
Built-in function of Python Description of the functions
● Tuple
Tuple, in Python, is identical to the list in several ways. Similar to lists, tuples
also possess the collection of different elements of numerous data types. The
components of the tuple are separated with the help of a comma "," and
enclosed in parentheses "( )."
Moreover, the system cannot modify the size, value, and numbers of the
elements in a tuple by itself.
Example:
>>> t = ("Hello", "Python’s world", 69)
>>> print (t [1 :]);
>>> print (t [0:1]);
>>> print (t);
>>> print (t + t);
>>> print (t * 3);
>>> print (type (t))
>>> t [2] = "hello";
Output:
When you write your first command and press enter, i.e.
print (t [1 :]);
Your console will print will print, “('Python’s world', 69)”.
When you write your second command and press enter, i.e.
print (t [0:1]);
Your console will print "('Hello',)".
When you write your third command and press enter, i.e.
print (t);
Your console will print, "('Hello', 'Python's world', 69)".
When you write your fourth command and press enter, i.e.
print (t + t);
Your console will print, "('Hello', 'Python's world', 69, 'Hello', 'Python's
world', 69)".
When you write your fifth command and press enter, i.e.
print (t * 3);
Your console will print, “('hello', 'Python world', 69, 'Hello', 'Python’s world',
69, 'Hello', 'Python’s world', 69)”.
When you write your sixth command and press enter, i.e.
print (type (t))
Your console will print, "< type 'tuple'>".
When you write your seventh command and press enter, i.e.
t [2] = "hello";
Your console will print will print;
Trace back (most recent call last):
File "main.py", line 8, in <module>
t [2] = "Hello";
Type Error: 'tuple' object does not support assignment
Chapter 6: Regular Expressions, Expression Statements, Loops in
Python
Like other computer programming languages, Python also possesses regular
expressions, statements, and loops. But, Python's expressions and loops are
unique and the totality of python programming.
All of these methods, functions, loops, and statements play a vital role in
building up an effective program for data analysis and for performing other
tasks as well, in Python. There is a various number of reasons behind the
additions and updates of these operational runners in the libraries of Python.
In this chapter, we will discuss the importance and functionalities of these
methods, while using Python, as a mode of programming.
Import statement
In Python, the import statement is a statement that is generally utilized to
import the modules whose capacities or factors can be utilized in the present
program. There are three different ways of utilizing
>>> Import:
>>> import <module name>
>>> [as <alias>].
>>> Print statement
The print statement was changed to the print () framework work in Python
with the release of Python 2.7
Explanation of some of the most used statements is as follows
● If-else statements in Python
Output:
When you will execute this code, your console screen will print a line as,
Enter your desired number =
After entering your number, if your entered number is an even number, your
program will print,
Your entered number is an even number:
Example – 2:
>>> n = int (input ("Enter first integer"));
>>> v = int (input ("Enter second integer "));
>>> w = int (input ("Enter third integer"));
>>> if n > v and n > w:
>>> print ("n is largest");
>>> if v > n and v > w:
>>> print ("v is largest");
>>> if w > n and w > v:
>>> print ("w is largest");
Output:
After compiling and executing this program, your computer will print this on
your console screen,
Enter first integer
Let’s say you have entered 69 as your first integer, i.e. “n”.
Your computer will now print another statement on your console screen,
Enter second integer
Let's say you have entered 70 as your second integer, i.e. "v."
Now, your computer will print another statement on the console screen,
Enter third integer
Let's say you have entered 69 as your third integer, i.e., "w."
In the above mentioned case, it will display this statement as our output.
v is largest
● The if-else statement
The if-else statement provides an else block in addition to the if statement,
which is executed in the false case of the first condition. When the condition
is true, then the if block is executed. Otherwise, the else block will be
considered true.
In Python, syntax for if else statement is as follows
>>> if condition:
>>> (block of statements)
>>> Else:
>>> (Block of else statements)
Example - 1:
>>> voterage = int (input ("Enter your age = "))
>>> if voterage >= 18:
>>> print ("You are eligible to cast vote!");
>>> else:
>>> print ("Sorry! You have to wait!");
Output:
When you will execute this program, your system will print the following
line to your console screen.
Enter your age =
If you enter an integer, which is equal or greater than 18, your screen will
display a message,
You are eligible to cast vote!
If you enter an integer, which is lower than 18, your screen will print this
message,
Sorry! You have to wait!
Example - 2:
>>> number = int (input ("Enter your desired number :"))
>>> if number % 2 == 0:
>>> print ("Your entered number is an even number!")
>>> else:
>>> print ("Your entered number is an odd number!")
Output:
When you execute this program, your screen will print a message,
Enter your desired number :
If you enter an even number, it will print,
Your entered number is an even number!
If you enter an odd number, it will print,
Your entered number is an odd number!
● The elif statement
The elif statement helps us to run multiple levels of conditions at the same
time. It must have if-and-if levels to perform the tasks, specified by the
program. It works only by taking up a series of 'True' conditions.
The syntax of elif statement is as follows
>>> if (expression 1):
>>> (block of statements);
>>> elif (expression 2):
>>> (block of statements);
>>> elif (expression 3):
>>> (block of statements);
>>> else:
>>> (block of statements);
● Python break statement
The break statement has its own unique importance in Python loop-oriented
programming. It shifts the execution pattern to the next lines by breaking up
the loop from the previous codes. With simple syntax, it gives back the
control to the required loops in the same larger program. Its syntax is simple.
break;
● Python continue Statement
In Python, this statement gives control of a program to the start of a loop. It
allows an individual to skips the rest of codes, and execution comes back to
the beginning. It has an important role in skipping and executing in special
conditions.
The syntax of continue statement is as follows
>>> loop statements
>>> continue;
>>> (the code to be skipped);
Example – 1:
>>> v = 0;
>>> while v != 10:
>>> print ("%d"%v);
>>> continue;
>>> v=v+1;
Output:
In this case, output will be an infinite loop.
Example - 2:
>>> n=1;
>>> for n in range (1,10):
>>> if n == 15;
>>> continue:
>>> print (%d"%n);
Output:
In this case, output will be a list of integers.
10
11
12
13
14
16
17
18
19
20
Pass
Example:
>>> for v in [1,2,3,4,5]:
>>> if v == 4:
>>> pass
>>> print "(pass when value is)",v
>>> print (v);
Output:
>>>
1 2 3 Pass when value is 4
45
>>>
● Import statement in Python
This statement is considered as the most valuable statement in python
programming. It makes possible the access of one module's functionality to
another module. Without import statement, Python is not able to perform up
to the mark. We use this statement, as its syntax of import statement.
import module;
Example:
>>> import document;
>>> last name = input("input your last name :")
>>> document.displayMsg(last name)
Output:
When you execute this program, your system will print a message to your
computer screen,
Input your last name :
For instance, you entered "Nasir", it will print,
Hi Nasir
Output:
When you execute this program, your console screen will print this,
Enter your desired number of rows
Let’s say you’ve entered “6”. It will print,
*
**
***
****
*****
******
● Else statement with for loop
The else statement is an essential part of many conditional statements. It is
also used in many other programming languages for the satisfaction of a
condition. In Python, the else statement can be executed inside a 'for loop.'
Example - 1:
>>> for v in range(0,8):
>>> print(v)
>>> else:print("Excluding break statement therefore for loop completely
exhausted.");
Output:
In this case, your console screen will print,
0
1
2
3
4
5
6
7
Since there is no break, for loop completely exhausted
Example – 2:
>>> for v in range(0,5):
>>> print(v)
>>> break;
>>> else:print("for loop is exhausted now!");
>>> print ("break statement is used therefore loop gets broken")
#The break statement is stopping the execution of the else statement.
Output:
In this condition, your console will print,
0
the break statement is used therefore loop gets broken
● Python while loop
In general, a while loop is responsible for enabling a part of the code to be
executed as long as the given condition is true. It is usually used in the case
where the iteration's quantity is not known in advance. While loop's syntax is
as follows.
>>> while expression:
>>> (statements);
Statement expression must be any valid Python expression concluding into
true or false. The True is any non-zero value, in this case.
Example – 1:
>>> v=1;
>>> while v<=11:
>>> print(v);
>>> v=v+1;
Output:
In this condition, your console will print a list of all integers, till 11.
1
2
3
4
5
6
7
8
9
10
11
● Infinite while loop in Python
If the condition provided in the while loop doesn't become false, the while
loop will never end, and the result will be an infinite while loop. To have a
True Condition, we use a non-zero value in while loop, and zero value to
indicate the False Condition
Example:
>>> variable = 1
>>> while variable != 2:
>>> v = int(input("Enter your desired number :"))
>>> print ("Entered value is %d"%(v))
Output:
In this results will be,
Enter your desired number : 67
Entered value is 67
Enter your desired number : 69
Entered value is 69
Enter your desired number : 68
Entered value is 68
Enter your desired number : 76 …
It will be an infinite loop.
● Else with Python while loop
Python empowers its developers to use the while loop with the while loop
inside it, as well. It executes the else square when the condition given in the
while articulation turns out to be false. Like for loop, on the off chance that
the while loop is broken using the break statement. At that point, the else
square won't be executed, and it will execute the announcement present after
an else square.
Example - 1:
>>> v=1;
>>> while v<=4:
>>> print(v)
>>> v=v+1;
>>> else:print("The while loop is broken");
Output:
In this case, your console will print,
1
2
3
4
The while loop is broken
Example – 2:
>>> v=1;
>>> while v<=5:
>>> print(v)
>>> v=v+1;
>>> if(v==3):
>>> break;
>>> else:print("The while loop is broken");
Output:
In this case, your console will print,
1
2
CHAPTER 7: Python Functions and File Handling
Python functions and file handling are the most important part of Python
programming. Without using these functionalities, no program can achieve
the desired results. Functions are easy to understand codes that can be called
anywhere in the main body of your program.
Example:
>>> n=20
>>> v= bin(n)
>>> print(v)
Output:
In this case, your console will print,
0b2020
● The bool ( ) Function
This function gives an output in Boolean type value by using truth testing
methods. It is an essential built-in function of Python. If there is any value
input, the result is true; otherwise, it prints false.
Example:
>>> v1=[5]
>>> print(v1, ‘is',bool(v1)
>>> v1= No-value
>>> print(v1, ‘is',bool(v1)
Output:
[5] is True
No-value is False
● The bytes ( ) Function
In Python, the bytes ( ) function is very helpful to get object in bytes. It
belongs to the command byte-array. Mostly, Python programming
professionals get help by generating objects through this command.
Example:
>>> string= "Hi Friend."
>>> array= bytes(string, ‘utf-8')
>>> print(array)
Results:
Hi Friend
● The callable ( ) Function
The concerned function investigates and shows up True when an object
seems callable otherwise, it shows False. This function may save time by
notifying the user about the availability of an object with just a single
command.
Example:
>>> v= 12
>>> print (callable(v))
Output:
False
● The compile ( ) Function
This function, compile ( ), works on the source code by using the compilers
of Python, and ultimately generate an object with that code. Later, we may
execute this code by using another function exec ( ) in the same program.
Example:
>>> yourcode_str= v=10\n w=15\n print("sum=",v+w)'
>>> yourcode=compile(yourcode_str, "sum.py','exec')
>>> print(type(yourcode))
>>> exec(yourcode)
>>> exec(c)
Output:
sum = 25
● The exec ( ) Function
The exec() function has a bit extra importance within the built-in functions of
Python. It runs the programs of python and produces the output. Without this
function, python programs cannot execute.
Example:
>>> v = 12
>>> exec('print(v==12)')
>>> exec('print(v+4)')
Output:
True
16
● The sum ( ) Function
In Python, when we work with arithmetic operations while using numerical
data, the Sum() function becomes inevitable. We use this function to perform
addition of values available in the list.
Example:
>>> v = sum([2, 5,4 ])
>>> print(v)
>>> v = sum([4, 2, 4], 10)
>>> print(v)
Output:
11
20
● The any ( ) Function
The any () function in Python provides the result or output in Boolean type
value which may be true or false.
It prints true when there is any value True on the list. But if there is no value
true, it gives False. It is also a very useful function for data scientist which
works on big data projects.
Example:
>>> V=[4, False,9]
>>> Print(any(V))
>>> V=[]
>>> Print(any(V))
Result:
True
False
● The ascii ( ) Function
The ascii() function has an important role in Python. The output value of this
function is always a string. We have to remember that it doesn't print other
ascii characters.
Example:
>>> vQ= 'Have a good day'
>>> print(ascii(vQ))
>>> wQ= 'Have a nice day'
>>> print(ascii(wQ))
>>> print(‘Have\xf6n a good day')
Output:
'Have a good day'
'Have\xf6n a good day'
'Have a nice day'
● The bytearray ( ) Function
The bytearray () function plays an important role in Python programming. To
create an object, this function helps users or software professionals with no
wastage of time.
Example:
>>> string1= "Computer Programming"
#string1 with encode ‘utf-8'
>>> array1= bytearray(string, ‘utf-8')
>>> print(array1)
Result:
bytearray(b'Computer Programming')
● The eval ( ) Function
The eval ( ) function plays an additional role in python programming. This
function executes itself in a running program to help the code manager to get
work done in speed.
Example:
>>> w= 6
>>> print(eval(‘w+1')
Output:
7
● The format ( ) Function
This format ( ) function in Python, makes the coding easier for every
programmer. By formatting the values and other given data, it saves the time
of a programmer.
Example:
>>> d, f and b are a type
# integer
>>> print(format(515, "d"))
# float arguments
>>>print(format(515.7898, "f"))
# binary format
>>> print(format(15, "b"))
Output:
245
363.790
35
● The frozenset ( ) Funcion
The frozenset() function, in Python programming, provides a changeable
frozen-set object. This is a very useful function for Python programming.
Example:
>>> letter = ('j', 'k', 'l', ‘m', 'p')
>>> frozset = frozenset(letter)
>>> print('Frozen set:', frozSet)
>>> print('set with no value:',frozenset())
Output:
Frozen set: ({'k', 'p', 'j', 'm', 'l'})
Set with no val: frozenset()
● The getattr ( ) Function
This function plays a very important role in python language. With the help
of this function, the user is able to get object’s attribute. Software
programmers use this function to assign names to the objects.
Example:
>>> class Details:
>>> age = 25
>>> name = "faheel"
>>> detail = Details()
>>> print('age:', getattr(detail, "age"))
>>> print('age:', detail.age)
Output:
age: 25
age: 25
● The globals ( ) Function
The globals ( ) function enables the user to get the table of global symbols,
with all the information of variables and methods. It is a mandatory function
to have all the symbols ready to use in any python program.
Example:
Id = 72
globals()['Id'] = 72
print(' My id :', Id)
Output:
My id : 72
● The hasattr ( ) Function
Hasattr ( ) function is based on Boolean type returns, i.e. True and False.
Example:
>>> v = [0, False, 5]
>>> print(any(v))
>>> v = []
>>> print(any(v))
Results:
True
False
● The iter ( ) Function
The iter ( ) function is commonly used as it deals with the values inside an
object mostly list. It prints the values in a list one by one.
Example:
# list of numbers
>>> list = [6,7,8,9,}
>>> listIter = iter(list)
# prints '6'
>>> print(next(listIter))
# prints '7'
>>> print(next(listIter))
# prints '8'
>>> print(next(listIter))
Output:
6
7
8
● The len ( ) Function
It is a very simple but extremely important function for python programming.
The users or programmers are able to measure the length of items by using
this function.
Example:
>>> stringW = '…Data…'
>>> print(len(stringW))
Result:
4
● The list ( ) Function
The list ( ) function is one of the most commonly used functions to generate a
complete list of set of given instructions.
Example:
>>> print(list())
#for empty list
# string
>>> String = 'abcde'
>>> print(list(String))
# tuple
>>> tuple = (1,2,3,4,5)
>>> print(list(Tuple))
# list
>>> list = [1,2,3,4,5]
>>> print(list(list))
Example:
>>> def localsBeta():
>>> return locals()
>>> def localstSenior():
>>> Alpha = True
>>> return locals()
>>> print('localsNoAutority:', localsBeta())
>>> print('localsHighAuthority:', localsAlpha())
Result:
localsBeta: {}
localsAlpha: {'present': True}
● The map ( ) Function
Them map ( ) function is really important as you can get an item’s list
processed under this function.
Example:
>>> def calculateAddition(n):
>>> return n+n
>>> numbers = (1, 2, 3, 4)
>>> result = map(calculateAddition, numbers)
>>> print(result)
# converting map object to set
>>> numbersAddition = set(result)
>>> print(numbersAddition)
Result:
<map object at 0x7fb04a6bec18>
● The delattr ( ) Function
This function is the most important as compared to all other functions. On
every step, a developer or user needs to delete attributes from a class and
shows error on calling the same attribute.
Example:
>>> class jobholder:
>>> ID= 76
>>> name= "Hiziya"
>>> email= "hiziya@company.com"
>>> def getinfo(self):
>>> print( self.id, self.name, self.email)
>>> J=jobholder()
>>> e.getinfo()
>>> delattrib(jobholder, ‘Job Description')
>>> e.getinfo()
Output:
76 Hiziya hiziya@company.com
● The divmod ( ) Function
This function performs a numerical operation on the given values. The
arguments that this function uses, are numeric values. In all numeric
operations. In Python, this function is frequently used and preferred.
Example:
>>> V = divmod(30,5)
>>> print(v)
Output:
(6, 0)
● The enumerate ( ) Function
The enumerate ( ) function is based on the sequence of index numbers.
Through using element’s sequence and index, it may generate an object
having numerical values.
Example:
>>> W = enumerate([4,5,6])
>>> print(W)
>>> print(list(W))
Output:
[(0, 4), (1, 5), (2, 6)]
● The dict ( ) Function
This function returns a dictionary. This function generates three types of
dictionary:
● Empty Dictionary: When there is no argument passed.
● Identical Key-value pair Dictionary: When there is a potential
argument given.
● Keyword and Value added Dictionary: When there is a keyword
argument.
Example:
>>> N = dict()
>>> V = dict(c=4,d=5)
>>> print(result)
>>> print(result2)
Output:
>>> {} #empty dictionary
>>> {'c': 4, 'd':5} #dictionary with values
● The filter ( ) Function
The filter ( ) function is used for the filtration of values by providing two
arguments, functions and variables. In case of (none) function, it returns only
TRUE.
Example:
>>> def filterdata(w):
>>> if w>4:
>>> return w
>> result = filter(filterdata,(1,2,7))
>>> print(list(result))
Output:
[7]
● The hash ( ) Function
The hash ( ) generates the numeric value through hash algorithm, in Python.
These values may be integers used for comparison of dictionary keys.
Example:
>>> V = hash(35)
>>> W = hash(35.6)
>>> print(v)
>>> print(W)
Output:
35
756783388388221
● The help ( ) Function
The help ( ) function is responsible to call help to assist the process of object
passage. Through additional parameters, this function share the help data
with you.
Example:
Information = help()
print(Information)
Output:
Help Centre!
● The min ( ) Function
The min ( ) function helps get the smallest or the most basic elements by
taking two arguments as input, elements list and Keywords list.
Example:
>>> V = min(2100,221,225)
>>> W = min(1000.25,2025.35,5625.36,10052.50)
>>> print(V)
>>> print(W)
Output:
221
1000.25
● The set ( ) Function
The set ( ) function generates an object by using itereable objects. This
function of python programming is considered as the base of programs.
Example:
>>> v = set('25')
>>> w= set('python')
>>> print(v)
>>> print(w)
Output:
{'2', '5'}
{'y', 'o', 't', 'h',', 'p', 'n'}
● The hex ( ) Function
The hex ( ) function converts the integer argument into hexadecimal string
value. This function makes the conversion easy for all programmers, software
developers, engineers and professional Python experts.
Example:
>>> n = hex(4)
>>> v= hex(140)
>>> print(n)
>>> print(v)
Output:
0x2
0x70
● The id ( ) Function
The id ( ) function generates an identity integer by the use of an argument.
Example:
>>> N = id("Python")
>>> V = id(1500)
>>> W= id([95,236,92,3225])
>>> print(N)
>>> print(V)
>>> print(W)
Output:
59696771728
66864236539
19945047867
● The setattr ( ) Function
This function is responsible for setting of an attribute of an object. It takes
different values and after execution of the function, it returns nothing.
Example:
>>> RollNo = 0 #RN- roll number
>>> Name = ""
>>> def_init_(my, RollNo, Name):
>>> my.RollNo = RollNo
>>> self.Name = Name
>>> V= Student(33,"Faheel")
>>> print(V.RollNo)
>>> print(V.Name)
>>> print(V.email) product error
>>> setattr(V, 'email','faheelnasir@gcaill.com') # adding new attribute
>>> print(V.email)
Output:
33
Faheel
faheelnasir@gcail.com
● The slice ( ) Function
The slice ( ) function gives slice from a group of elements. Initially it takes a
single argument, but a second function requires three arguments to proceed.
Example:
>>> V = slice(7)
>>> W = slice(0,7,3)
>>> print(V)
>>> print(W)
● The sorted ( ) Function
We use this function for the sorting of elements. Sorting, due to this function
is in ascending order. To proceed, this function uses normally four values.
Example:
V = "python"
W = sorted(V) # sorting string
print(W)
● The next ( ) Function
The next ( ) function enables to get next element from the given group.
Through two arguments, this function produces with a single element.
Example:
>>> V = iter([128, 16, 42])
>>> W= next(V)
>>> print(W)
>>> W = next(V)
>>> print(W)
>>> W= next(V)
>>> print(W)
#V is a number
#W is an item
Output:
128
16
42
● The input ( ) Function
The input ( ) function is specially used for taking instructions from the
programmer or software developer or the user. After getting information, it
converts that value into program required data format.
Example:
>>> value = input("Please insert your desired value: ")
>>> print("You entered:",value)
Output:
Please Insert your desired value: 22
You entered: 22
● The int ( ) Function
The int ( ) function is designed to get integers, normally users use it to
converts strings and other data structures into specified integral values.
Example:
>>> n = int(15) # integer
>>> v = int(15.52) # float
>>> w = int('15') # string
>>> print("Int val:",a, b, c)
Output:
Int val : 15 15 15
● The pow ( ) Function
We use pow ( ) function to compute number’s power to define it for some
specific results needed for the project or program. It is really an important
function to carry out many algebraic solutions for numbers.
Example:
>>> Positive v, Positive w (v**w)
>>> print(pow(2, 3))
>>> Negative v, Positive w (-v**w)
>>> print(pow(-2, 3))
>>> Positive v, Negative w (v**-w)
print(pow(2, -3))
>>> Negative v, Negative w (-v**-w)
print(pow(-2, -3))
Output:
8
8
● The print ( ) Function
The print ( ) function responsible to print an element or object on screen.
Example:
>>> print("Hello! To the world of Python Programming!")
>>> v = 7
>>> print("v =", v)
>>> w = v
>>> print('v =', v, '= w')
Output:
Hello! To the world of Python Programming!
v=7
v=7=w
● The range ( ) Function
The range ( ) function provides the sequence that begins at 0 in general, it
increases by 1 and stops on some specific number.
Example:
>>> print(list(range(9,12)))
>>> range(start, stop)
Output:
[10,11]
● The reversed ( ) Function
The reversed ( ) function returns the reverse sequence of a given sequence.
Example:
>>> string = 'Hello'
>>> print(list(reversed(string)))
>>> tuple = ('H', 'e', 'l', 'l', 'o')
>>> print(list(reversed(tuple)))
>>> range = range(10, 12)
>>> print(list(reversed(range)))
>>> List = [1, 2, 7, 7, 9]
>>> print(list(reversed(List)))
Output:
['o', 'l', 'l', 'e', ‘H']
● The round () Function
The round ( ) function is mostly used when there are decimals used in the list
of numbers.
Example:
>>> print(round(8))
>>> print(round(10.4))
>>> print(round(6.6))
Output:
8
10
7
● The str ( ) Function
The str ( ) transforms any value into string. This conversion function helps
user to get things done quickly.
Example:
>>> str('6')
Output:
'6'
● The tuple ( ) Function
The tuple ( ) function generates an object through any function. This function
allows users to get their required object by just writing a simple syntax.
Example:
>>> n = tuple()
>>> print('n=', n)
>>> v = tuple([2, 8, 10])
>>> print('v=', v)
>>> n = tuple('Python')
>>> print('n=',n)
>>> n = tuple({4: 'four', 5: 'five'})
>>> print('n=',n)
Output:
n = ()
v= (2, 8, 10)
n= ('P', 'y', 't', 'h','o','n')
n= (4, 5)
● The type ( ) function
The type ( ) function is normally applied to understand the data type on an
element. With three arguments, the type function gives an object.
Example:
>>> V = [4, 5] #LIST
>>> print(type(V))
>>> W = {4: 'four', 5: 'five'} #Dictionary
>>> print(type(W))
>>> class Python:
>>> n = 0
>>> InstanceOfPython = Python()
>>> print(type(InstanceOfPython))
Output:
<class 'V'>
<class 'W'>
<class '__main__.Python'>
● The vars ( ) function
The vars ( ) function returns the attributes which belongs to the dictionary. It
is most commonly used function of python.
Example:
>>> class Python:
>>> def _init_(my, v = 7, w = 9):
>>> my.v = v
>>> my.w = w
>>>InstanceOfPython = Python()
>>>print(vars(InstanceOfPython))
Output:
{'w': 9, 'v': 7}
● The zip ( ) Function
The zip ( ) function gives an object having the same index with several
containers. Through this function, results can be produced in an achieved or
zip form.
Example:
>>> numericalList = [4,5, 6]
>>> stringList = ['four', 'five', 'six']
>>> V = zip()
>>> VList = list(V)
>>> print(VList)
>>> V= zip(numberList, stringList)
>>> VSet = set(result)
>>> print(VSet)
7.2 File Handling of Python
Python supports file handling and it also enables clients to deal with reading
and writing of any document, alongside various methods to deal with the
available file or document. The concept of file handling is present in many
different computer programming languages, however the usage of file
handling is either muddled or protracted in other languages. In Python, the
idea of file handling is similar yet different. In Python, file handling is really
simple.
Python provides multiple unique features and functions to handle the files. It
distinguishes other high-level computer programming languages on the basis
of the structural organization of file handling and management. It is easy to
learn and implement coding module in Python. We should begin with
Reading and Writing the files. For this, the syntax is mentioned below.
open(filename, mode)
● File Opening Using Function open()
We use open () function for reading and writing the file. As mentioned
earlier, it restore an object in file format. Generally, open ( ) works alongside
two contentions, that acknowledges file management. It's syntax is mentioned
below.
Object File= open(<name>, <mode>, <buffering>)
● Closing of File Using Function close ()
After the completion of the program, the programmer must close the file by
using python’s script, close ( ).
It secures the file from external threats and prevents the manipulation of
functionalities. It’s syntax is mentioned below.
file.close()
Example:
Filenvw=open("file.txt","c")
if filenvw:
print("opened successfully")
filenvw.close()
Chapter 8: OOP Concepts in Python
Python object-oriented programming concepts are playing a vital role in the
software industry. It has all the concepts of object-oriented programming.
There are many other languages of the same core programming family, but
python is based on OOP concepts from the very beginning. Here, a software
expert has the liberty to call functions, objects, and classes to perform any
programming task. This language is highly recommended for data science
concepts.
Output:
ID number: 78
Name: Nasir
Example:
>>> class Student:
>>> count = 0
>>> def __init__(self):
>>> Student.count = Student.count + 1
>>> s1=Student()
>>> s2=Student()
>>> s3=Student()
>>> print("The number of students:",Student.count)
Output:
The number of students: 3
Example:
>>> class Workers:
>>> def __init__(my,name,age):
>>> my.name = name;
>>> my.age = age
>>> W = worker("Cindy",115,22)
>>> print(getattr(W,'name'))
>>> setattr(W,"age",27)
>>> print(getattr(s,'age'))
>>> delattr(s,'age')
>>> print(s.age)
Output:
Cindy
27
True
AttributeError:There is no attribute 'age' in Student' object.
● Built-in class attributes
A class in Python also contains some class attributes (built-in) which give
information about the class.
Here is the list of built-in class attributes:
__dict__
It is for providing the dictionary containing information about the class
namespace.
__doc__
It is to contain a string which has the class documentation
__name__
It accesses the class name.
__module__
It accesses the module in which this class is defined.
__bases__
It is used to obtain a tuple.
Example:
>>> def __init__(my,name,roll number,age):
>>> my.name = name;
>>> my.rollbumber = roll number;
>>> m.age = age
>>> def display_details(my):
>>> print("Name:%s, Roll Number:%d, age:%d"%(my.name,my.roll
number))
>>> Y = Student("Jack",10,17)
>>> print(y.__doc__)
>>> print(y.__dict__)
>>> print(y.__module_)
Output:
None
{'name': 'Jack', 'Roll number': 10, 'age': 17}
__main__
Output:
barking dog
Animal Speaking
Example:
>>> class Animal:
>>> def speak(self):
>>> print("Speaking Animal")
#The child class Dog inherits the base class Animal
>>> class Dog(Animal):
>>> def bark(self):
>>> print("barking dog")
#The child class Dogchild inherits another child class Dog
>>> class DogChild(Dog):
>>> def eat(self):
>>> print("Bread eating...")
>>> d = DogChild()
>>> d.bark()
>>> d.speak()
>>> d.eat()
Output:
barking dog
Speaking Animal
Bread eating...
Chapter 9: Modules, Exceptions and Arrays in Python
Python’s modules, exceptions and arrays are most important components of
object-oriented Python programming. In Python, we use them both, time by
time to have a better understanding with the usage of code in a very logical
way. These programming methods are also used in other high-level computer
programming languages, and they possess many popular frameworks.
Because of their usage it’s easy to transform the complexities of
programming into simple coding. Let’s discuss them one by one.
Output:
Calculated Mode 2
Example:
>>> import statistics
>>> data = [7, 8, 9, 10, 11]
>>> print("Standard Deviations of sample data is: % s "
>>> % (statistics.stdev(data)))
Output:
Standard Deviation of sample data is: 1.5811388300841898
● The median_low ()
The median_low ( ) function is used to return the low median of numeric data
in your given list.
Example:
>>> import statistics
# simple list of a set of integers
>>> setofdata1 = [4, 6, 2, 5, 7, 7]
# Print low median of the data-set
>>> print ("data-set Low median is % s "
>>> % (statistics.median_low(setofdata1)))
Output:
Low median of the data-set is 5
● Median_high ()
The median_high () function is used to calculate the high median of numeric
data in your entered list.
Example:
>>> import statistics
# list of set of the integers
>>> setofdata = [2, 1, 7, 6, 1, 9]
>>> print("High median of data-set is %s "
>>> % (statistics.median_high(setofdata)))
Output:
High median of the data-set is 6
● The Math module of Python
The Math module of Python contains the mathematical functions to perform
most of the mathematical calculations.
There are two constants as well:
● Pi (π)
Pi is a well-known mathematical constant and is defined as the ratio of
circumstance of a circle to its diameter. Its value is or approximately
3.141592653589793.
● Euler's Number (e)
Euler’s Number is the base of natural logarithmic, and its value is
approximately 2.718281828459045.
A few most used Math modules are elaborated below:
● The math.log10() function
This function is used to calculate base 10 logarithm of the number.
Example:
>>> import math
>>> v=13 # small value of x
>>> print('log10(v) is :', math.log10(v))
Output:
log10(v) is : 1.1139433523068367
● The math.sqrt () function
This function calculates the root of number.
Example:
>>> import math
>>> n = 20
>>> v = 14
>>> w = 17.8995
>>> print('square root of 20 is ', math.sqrt(n))
>>> print('square root of 14 is ', math.sqrt(v))
>>> print('square root of 17.8995 is ', math.sqrt(w))
Output:
square root of 20 is 4.47213595499958
square root of 14 is 3.7416573867739413
square root of 17.8995 is 4.230780069916185
● The math.expm1() function
This function is used to calculate “e” raised to the power of any number
minus 1. “e” is the base of natural logarithm.
● The math.cos() function
This function is used to calculate the cosine of any number in radians.
Example:
>>> import math
>>> angleInDegree = 60
>>> angleInRadian = math.radians(angleInDegree)
>>> print('Given angle :', angleInRadian)
>>> print('cos(x) is :', math.cos(angleInRadian))
Output:
>>> Given angle : 1.0471975511965976
>>> cos(x) is : 0.5000000000000001
● The math.sin() function
This function is used to calculate the sine of any number, in radians.
Example:
>>> import math
>>> angleInDegree = 60
>>> angleInRadian = math.radians(angleInDegree)
>>> print('Given angle :', angleInRadian)
>>> print('sin(v) is :', math.sin(angleInRadian))
Output:
Given angle: 1.0471975511965976
sin(v) is: 0.8660254037844386
● The math.tan() function
This function is used to return the tangent of any number, in radians.
Example:
>>> import math
>>> angleInDegree = 60
>>> angleInRadian = math.radians(angleInDegree)
>>> print('Given angle :', angleInRadian)
>>> print('tan(v) is :', math.tan(angleInRadian))
Output:
Given angle : 1.0471975511965976
tan(v) is : 1.7320508075688767
● The Sys module of Python
The sys module provides access to system-specific functions. It changes the
Python Runtime Environment to enable the user to get parameters, variables
and articles.
● Importing sys function
First of all, we need to import the sys module in the program before starting
the use of functions and before calling any function.
● The sys.modules’ function
These functions are used to perform some really important tasks on system
and Python Runtime Environment in python programming.
● Function of sys.argv:
This function is used for arguments.
● Function of sys.base_prefix:
This function is used for startup.
● Function of sys.byteorder
This function is used to get byterorder.
● Function of sys.maxsize
This function is used to get large integer.
● Function of sys.path
This function is used to set the path.
● Function of sys.stdin
This function is used to restore files.
● Function of sys.getrefcount
This function is used to get reference count of an object.
● Function of sys.exit
This function is used to exit from Python command prompt.
● Function of sys executable
This function is used to locate the python in system.
● sys.platform
This function is used to identify Platform.
● The Collection Module in Python
Collection module plays an important role as it collects major data formats or
data structures such as list, dictionary, set and tuple. This function is
responsible to improve the functionality of the current version of python.
It is defined as a container that is employed to conserve collections of data,
for example, list.
● The function of namedtuple() in Collection Module
This function produces a tuple object without causing any issue of indexing.
Example:
>>> Faheel = (Faheel', 25, 'Male')
>>> print(Faheel)
Output:
('Faheel', 25, 'Male')
● OrderedDict() function
This function generates dictionary object with key that can overwrite data
inside.
Example:
>>> import collections
>>> d1=collections.OrderedDict()
>>> d1['N']=15
>>> d1['V']=20
>>> d1['W']=25
>>> d1['T']=30
>>> for k,v in d1.items():
>>> print (k,v)
Output:
N 15
V 20
W 25
T 30
● Function defaultdict()
This function produces an object similar to dictionary.
Example:
>>> from collections import defaultdict
>>> number = defaultdict(int)
>>> number['one'] = 1
>>> number['two'] = 2
>>> print(number['three'])
Output:
0
● Counter() function
This function counts the hashable objects after reviewing the elements of list.
Example:
>>> A = Counter()
>>> Vlist = [1,2,3,4,5,7,8,5,9,6,10]
>>> Counter(Vlist)
>>> Counter({1:5,2:4})
>>> Wlist = [1,2,4,7,5,1,6,7,6,9,1]
>>> c = Counter(Wlist)
>>> print(A[1])
Result:
3
● The function deque()
This function facilitates addition and removal of elements from both ends.
Example:
>>> from collections import deque
>>> list = ["n","v","m"]
>>> deq = deque(list)
>>> print(deq)
Output:
deque(['n', 'v', 'm'])
● Python OS Module
Python’s OS module provides functions utilized for interacting with the
operating system and also gets the related data about it. The operating system
comes under Python's standard utility modules. Python operating system
module allows us to work with the files, documents and directories. Some of
OS module functions are as follows,
● os.name
This function provides the name of the operating system module it imports.
It can register 'posix', 'nt', 'os2', 'ce', 'java' and 'riscos'.
Example:
>>> import os
>>> print(os.name)
Output:
posix
● os.getcwd()
This function restores the Current Working Directory (CWD) of the file.
Example:
>>> import os
>>> print(os.getcwd())
Output:
C:\Users\Python\Desktop\ModuleOS
● os.error
The functions in this module defines the OS level errors in case of invalid file
names or invalid file path.
Example:
>>> import os
>>> filename1 = 'PythonData.txt'
>>> f = open(filename1, 'rU')
>>> text = f.read()
>>> f.close()
>>> print('Difficult read: ' + filename1)
Output:
Difficult read: PythonData.txt
● os.popen()
This function opens a file, and it gives back a file object which contains
connection with pipe.
● The datetime Module
This is an imported module that allows to create date and time objects. It
works to conduct many functions related to date and time.
Example:
>>> import datetime;
#returns the current datetime object
>>> print(datetime.datetime.now())
Output:
2018-12-18 16:16:45.462778
● The Comma Separated values (CSV) File
This is a simple file format that arranges tabular data. It is used to store data
in tabular form or spreadsheet that can be exchanged when needed. This is a
Microsoft excel supported data form.
● The CSV Module Functions in Python
This module helps in reading and writing CSV files. It takes the data from
columns and stores it to use in future.
● The function csv.field_size_limit
This function is used to maximize field size.
● The function csv.reader
This function is used to read information or data from a csv file.
● The function csv.writer
This function is used to write the information or data to a csv file. This
functions have major role in CSV module.
9.2 The Exceptions in Python Programming
Exceptions are basically interruption that stops a running program. They are
mistakes, bugs or errors in a code. In python, they are handled differently.
● The Common Exceptions in Python
Here are some common exceptions that may occur in python. Every
professional Python programmer is very well familiar with these errors or
exceptions.
● The exception of ZeroDivisionError
This exception occurs when a number is divided by zero.
● The exception of NameError
This exception occurs when a name is not found.
● The exception of IndentationError
This exception occurs when incorrect indentation is given.
● The exception of IOError
This exception occurs when Input Output operation fails.
● The exception of EOFError
This exception occurs when the end of the file is reached, and still operations
are being performed.
● Unhandled Exceptions
Example:
>>> n= int(input("Enter a:"))
>>> v = int(input("Enter b:"))
>>> w= a/b;
>>> print("x/y = %d"%c)
>>> print("Hello I am a teacher")
Output:
Enter a:10
Enter b:0
Traceback (most recent call last):
File "exception-test.py", line 3, in <module>
c = a/b;
ZeroDivisionError: division by zero
● The finally block
This exception is used to run a code before the try statement. It’s syntax is as
follows,
>>> try:
>>> (block of code)
>>> (this may throw an exception)
>>> finally:
>>> (block of code)
>>> (this will always be executed)
Example:
>>> try:
>>> fileptr = open("file.txt","r")
>>> try:
>>> fileptr.write("Hi I am good")
>>> finally:
>>> fileptr.close()
>>> print("file closed")
>>> except:
>>> print("Error")
Output:
file closed
Error
● The Exception Raising in Python
The raise clause in python is used to raise an exception. It’s syntax is as
follows,
Raise exception_class,<value>
● The Custom Exception in Python
This exception enables programmers to generate exceptions that has already
been launched with the program.
Example:
>>> class ErrorInCode(Exception):
>>> def __init__(self, data):
>>> self.data = data
>>> def __str__(self):
>>> return repr(self.data)
>>> try:
>>> raise ErrorInCode(2000)
>>> except ErrorInCode as ae:
>>> print("Received error:", ae.data)
Output:
Received error: 2000
● Update
This operation is used to update an element at the given index.
● Array Generation
>>> array import *
>>> MyarrayName = array(typecode, [initializers])
● Accessing array elements
The array elements accessibility can be done by using the respective indices
of the concerned elements.
Example:
>>> import array as arr
>>> a = arr.array('i', [1, 3, 5, 87])
>>> print("First element:", a[0])
>>> print("Second element:", a[1])
>>>print("Second last element:", a[-1])
Output:
First element: 1
Second element: 3
Second last element: 8
● We have to remember that the arrays are changeable, and elements
can be changed in a similar to lists.
● A combination of arrays makes the process fast and saves time.
The array can reduce code's size.
● Deletion can be done by using the del statement, in Python.
● Length of an Array
The length of an array can be described as the number of elements in an
array. It returns an integer value that is equal to the total number of the
elements present in the concerned array. It’s syntax is as follows,
len(array_name)
Example:
>>> n=arr.array('d',[1.2 , 2.2 ,3.2,3,6,7.8])
>>> v=arr.array('d',[4.5,8.6])
>>> w=arr.array('d')
>>> w=n+v
>>> print("Array w = ",w)
Output:
Array w= array('d', [1.2, 2.2, 3.2, 3.6, 7.8, 4.5, 8.6])
Example:
>>> import array as arr
>>> x = arr.array('i', [5, 10, 15, 20])
>>> print("First element:", x[0])
>>> print("Second element:", x[1])
>>> print("Second last element:", x[-1])
Output:
First element: 5
Second element: 10
Second last element: 15
Chapter 10: Libraries in Python
In the previous chapters, we studied the important concepts of Python, such
as data structures, built-in functions, variables, exceptions, methods, for
loops, and statements. In the following chapter, we will deeply study the
modules, libraries, and packages of Python that can be important for any of
the projects. To import is the most important concept within Python. So, by
the use of this concept, we can call millions of the libraries that can be used
in Python.
Moreover, Python programming and data science are parallel to each other.
Python is an unbelievable language for data science, and it's important for
individuals who need to begin in the field of data science. It provides
countless cluster libraries and systems to provide a decision for working with
data science in a spotless and very productive manner. The different systems
and libraries accompany a particular reason for use and should be picked by
your prerequisite.
10.1 Python General Libraries
Python is known as a "batteries-included programming language." Python
essentially implies and accompanies various pre-packaged libraries. In any
case, there is a number of different libraries accessible for the translated,
abnormal state. Moreover, Python is a universally useful programming
language.
Among different elements that are being added to the prevalence of Python,
they have a humongous gathering of libraries is a noteworthy one. Most
libraries and bundles are a bundle or group of many programming languages,
which provides developer access. Here are some of the most important
languages that are used in Python.
One of the most important general Python libraries is "Requests." It intends
to make HTTP demand increasingly human-accommodating and less
difficult. This library is authorized under the Apache2 permit and written in
Python; Requests is a true standard used by Python developers for making
HTTP demands while using Python.
Using the Requests library for sending HTTP solicitations to a server, it
additionally permits including structure information, content, header, multi-
part documents, and so forth with them. With the library, designers do not
need to add a question to the URL or structure encode the POST information
physically.
The Requests library abstracts the various complexities of making HTTP
demands in a basic API so developers may concentrate more on
communication with the administrators. This library, additionally, offers
authority support for Python 2.7, Python 3.4, or more and works perfectly
with PyPy as well.
Special Features:
● It allows multi-part record transfers and spilling downloads.
● It automatically substances the disentangling and programming
decompression.
● It's browser-style is SSL confirmation.
● In this library, features can be modified and improved according to
prerequisites.
● This library keeps-alive and provides Pooling Supports
international domains and URLs.
● PIL
PIL or Python Imaging Library is a free Python library that adds a picture
capacity to the Python variables. In basic terms, PIL permits controlling,
opening, and sparing different picture records that are being organized in
Python. This library was developed by Alex Clark and Contributors. Pillow is
a sub-set of the PIL library.
Furthermore, this library offers incredible picture handling abilities; PIL
offers a powerful inward portrayal and broad record organization support.
The concerned central Python library is intended for offering quick access to
information put away in a couple of fundamental pixel designs.
Special Features:
● This library is effective in investigating bolsters by utilizing the
show() strategy.
● This library is Ideal for group handling applications.
● In the concerned library variables and peruses a huge scope of
picture document designs.
● PIL additionally offers BitmapImage, PhotoImage, and Windows
DIB interfaces.
● This library supports the relative discretionary changes, shading
space transformations, separating with a lot of implicit
convolution parts, picture resizing and turn, and point activities.
● In this library, the histogram technique is permitted hauling a few
measurements out of a picture, can be utilized for programmed
differentiate upgrade and worldwide factual investigation.
● Scrapy
Scrapy is also a free and open-source Python structure that is broadly utilized
for web and various different assignments, including mechanized testing and
information mining. Initially, Scrapy was developed for web-based
scratching, yet it has updated to satisfy different purposes over its course.
This library also offers a quick and abnormal state strategy for creeping sites
and separating organized information from websites.
This library is written in Python. Scrapy is worked around errors and bugs
that are essentially independent crawlers, which are given with too many
guidelines. Complying with the DRY standard, Scrapy makes it simpler to
assemble and scale undeniable web slithering undertakings.
Special Features:
● Scrapy is easy to compose a bug to slither a site and concentrate
information.
● It follows the DRY rule.
● This Python library offers a web-slithering shell that enables
engineers to test a website's conduct.
● This library supports sending out scratched information utilizing
the direction line
● Tkinter
When we work with Tkinter, Python offers a simple and quick path for the
development of GUI applications. This library is considered as the standard
GUI library for Python programming. It offers an amazing item situated
interface for the Tk GUI toolbox. We should remember that developing a
GUI application while utilizing Tkinter is simple. You just have to pursue
these basic advances:
Special Features:
● This library comes with a scope of gadgets that help geometry the
executive's strategies.
● It provides eases while creating GUI applications.
● Tkinter supports a powerful object-situated interface.
● Six
We have to admit the fact that six is the simplest of Python libraries. It is an
amazing Python library that is intended to smooth out the contrasts between
Python 2 and Python 3 forms.
Six is developed for supporting codebases that can work on both Python 2
and Python 3 without any requirement of adjustment.
The Six libraries considered super-simple to use on account of being offered
as a solitary Python document. Consequently, Six is absurdly simple to
duplicate a library into a Python venture. The name Six reflects Python 2 x
Python 3.
Special Features:
● Six is simple to utilize the capacities for making Python code
perfect with both Python 2 and Python 3.
● This library supports each version of Python, since Python 2.6.
● It is too easy to use Six as contained in a solitary Python
document.
● Pygame
Pygame is an open-source and free Python library that is intended for
achieving video-based and sound-based application improvement in Python.
Particularly it supports two-dimensional gaming ventures. So, it is mostly
used by both new and expert Python game developers.
In a Python compiler or IDE, Pygame utilizes the SDL, i.e., Simple
DirectMedia Layer library. Like the SDL library, the Pygame library is
profoundly convenient, and it offers help for a wide number of stages and
working frameworks.
Pygame is conceivable to escort applications created utilizing Pygame on
Android-based gadgets, like cell phones and tablets. For many reasons, you
should prefer pgs4a, which is a Pygame subset for Android.
Special Features:
● This library doesn't request OpenGL.
● It helps you in a simple way to utilize a multi-center CPU.
● While using this library, no GUI is required for utilizing every
single accessible capacity.
● This library provides support for a wide scope of stages and
working frameworks.
● This library is simple to utilize.
● Pygame uses Assembly Code and advanced C code for actualizing
the central capacities.
● Bokeh
Bokeh is an instinctive portrayal library for the Python programming
language; It grants imagining data in a stunning and critical course inside
contemporary web programs. The data portrayal library encourages the
creation of dashboards, data applications, and keen plots.
Despite offering a brief and lovely improvement of versatile plans, the Bokeh
library in like manner extends its capacity with the best of knowledge over
spilling or tremendous datasets and databases.
Special Features:
● While using this library, authentic plots with clear headings can be
built easily without any complexity.
● Bokeh portrayals can be successfully introduced into two of the
most standard. Python frameworks, Django and Flask.
● It provides the capacity to make dazzling and natural data
recognitions in multiple computer programming language dialects.
● Asyncio
This library is utilized for composing simultaneous code by utilizing the
async and anticipates grammar by the developers. In the larger part of the
program, the asyncio library is perfect for IO-bound and high-level organized
system source code.
Asyncio has been utilized for the structural difference of Python non-
concurrent frameworks that offer database association with the libraries,
circulated undertaking lines, elite system, and web servers, and significantly
much more. The concerned library accompanies various high-level and low-
level APIs.
Special Features:
● This library is used for the implementation of protocols by
employing transport.
● While using this library, you will find Python codes easy and
straightforward.
● Asyncio helps in the generation of many different loops.
Special Features:
● Numpy is a very interactive library, and it's easy as well.
● While using Numpy, Mathematical problems are solved with ease.
● Pandas
In Python, we use two-dimensional tables to analyze the data like in SQL or
Excel. Initially, Python did not have this feature. But then Pandas was
introduced. Without a doubt, Pandas is the "SQL of Python." In short, Pandas
is the library that may help us to handle two-dimensional data tables in
Python. In many cases, it's similar to SQL, though.
Moreover, Pandas is based on the NumPy bundle, which means a great
amount of the structure of NumPy is used or duplicated to develop Pandas.
Information in pandas is frequently used to bolster factual examination in
SciPy, plotting capacities from Matplotlib, and machine learning calculations
in Scikit-learn.
Also, Jupyter Notebooks offer a decent situation for utilizing pandas to
perform information investigation and demonstrating, yet pandas can
likewise be used in content tools simply.
Jupyter Notebooks enables a developer to execute code in a specific cell
instead of running the whole record. This spares a ton of time when working
with enormous datasets and complex changes. Scratchpad likewise gives a
simple method to imagine pandas' DataFrames and plots. Indeed.
Pandas is mostly known for giving information outlines in Python. This is an
outstanding library for information examination, contrasted with other area
explicit dialects like R. By using Pandas; it's simpler to deal with missing
information, bolsters working with contrastingly filed information assembled
from numerous various assets, and supports programmed information
arrangement.
Furthermore, it provides devices the information examination and
information structures like consolidating, molding, or cutting datasets, and it
is additionally exceptionally viable in working with information identified
with time arrangement by giving hearty apparatuses to stacking information
from Excel, level documents, and databases.
Utilizing the Pandas library makes it simpler and instinctive for programmers
to work with named or social data. It also offers expressive, quick, and
adaptable data structures. Pandas are made to fill in as the essential elevated
level structure shut for doing data examination, which is utilized while using
Python as a mode of programming.
One of the most prominent and dominant features of Pandas is to interpret
complex data activities utilizing negligible a couple of directions. Also, the
Artificial Intelligence library has no shortage of work in techniques for
consolidating, separating and gathering data. It additionally
Highlights time-arrangement usefulness.
Special Features:
● While using Pandas, operations of custom type can be completed
significantly.
● With the use of Pandas, data manipulation becomes simpler and
easier.
● When Pandas is used with other Python libraries and tools, it
provides excellent results.
● The Matplotlib
Matplotlib is a two-dimensional plotting library with extraordinary
representation modules for Python. It is equipped for delivering top-notch
figures in various printed version organizations and intelligent cross-stage
conditions. Besides being utilized in Python shell, Python contents, and
IPython shell, Matplotlib can likewise be utilized in:
● Jupyter Notebook
● Web application servers
● GUI tool boxes
As said by the official site of Matplotlib, this Python library tries to "make
simple things simple and hard things conceivable." The 2D plotting Python
library permits producing bar graphs, mistake diagrams, histograms, plots,
scatter plots, and so on with fewer lines of code.
Maybe, the best advantage of representation is that it permits us visual access
to enormous measures of information in effectively absorbable visuals.
Matplotlib comprises a few plots like line, bar, and disperse histogram, and
so forth.
Matplotlib is a Mathematical Plotting Library in Python. It is a library that is,
for the most part, utilized for information representation, including 3D plots,
histograms, picture plots, scatterplots, bar graphs, and power spectra with
bright highlights for zooming and searching for gold in various printed copy
designs. It bolsters practically all stages, for example, Windows, Mac, and
Linux. This library likewise fills in as an augmentation for the NumPy
library. Matplotlib has a module pyplot which is utilized in representations,
which is frequently contrasted with MATLAB.
These libraries are the best for amateurs to begin information science
utilizing the Python programming language. There are numerous other
Python libraries accessible, for example, NLTK for standard language
preparing, Pattern for web mining, Theano for profound learning, IPython,
Scrapy for web scratching, Mlpy, Stats models, and the sky is the limit from
there.
Special Features:
● It has handy properties, font properties, line styles, etc. through an
object-oriented interface.
● MATLAB interface supports the simple plotting of data.
● It has secondary x/y axis support to represent two dimensions.
● This library supports multiple operating systems.
● Scikit-Learn
Scikit-learn gives a scope of administered and solo learning calculations by
means of a predictable interface in Python. It is authorized under a lenient
rearranged BSD permit and is dispersed under numerous Linux
disseminations, empowering scholastic and business use. The library is based
upon the SciPy (Scientific Python) that must be introduced before you can
utilize sci-kit-learn.
There are a few Python libraries that give strong executions of the scope of
machine learning calculations. Outstanding amongst other known is Scikit-
Learn, a bundle that gives proficient adaptations of countless basic
calculations. Scikit-Learn is described by a perfect, uniform, and streamlined
API, just as by extremely helpful and complete online documentation. An
advantage of this consistency is that once you comprehend the fundamental
use and language structure of Scikit-Learn for one sort of model, changing to
another model or calculation is extremely direct.
Undoubtedly the fanciest things in Python are Machine Learning and
Prescient Investigation. Also, the best library for that is Scikit-Learn, which
essentially characterizes itself as "Machine Learning in Python." Scikit-Learn
has a few techniques, fundamentally covering all that you may require in an
initial couple of long periods of your information profession: relapse
strategies, characterization strategies, and bunching, just as model approval
and model determination.
This prevalent library is utilized for AI in information science with a different
order, relapse, and grouping calculations, which offers help vector machines,
innocent Bayes, angle boosting, and sensible relapse. SciKit is intended to
interoperate with SciPy and NumPy.
Special Features:
● Capability to extract features from images and text
● Can be utilized again in several contexts
● Scipy
There are scipy library and scipy stack. The vast majority of the libraries and
bundles are a piece of the Scipy stack (that is for logical processing in
Python). And one of these parts is simply the Scipy library, which gives
proficient answers for numerical schedules (the math stuff behind AI
models). These are incorporation, introduction, improvement, and so forth.
Scipy gives the center scientific strategies to do the unpredictable AI forms in
Scikit-learn.
It is an open-source library utilized for registering different modules, for
example, picture preparing, joining, insertion, unique capacities,
enhancements, straight variable based math, Fourier Transform, grouping,
and numerous different undertakings. This library is utilized with NumPy to
perform a proficient numerical calculation.
Special Features:
● Comfortably handles mathematical operations
● Provides effective and efficient numerical routines, such as
numerical integration and optimization, using sub-modules
● Supports signal processing
● TensorFlow
Anyone engaged with AI machine learning tasks utilizing Python must have,
at any rate, knew about TensorFlow. Created by Google, it is an open-source
representative math library for numerical calculation utilizing information
stream diagrams. The scientific activities in a normal TensorFlow
information stream diagram are spoken to by the chart hubs. The chart edges,
then again, speak to the multidimensional information exhibits, a.k.a.
Tensors, that stream between the diagram hubs.
TensorFlow parades an adaptable design. It enables Python engineers to
convey calculation to one or numerous CPUs or GPUs in a work area, cell
phone, or server without the need for revising code. All libraries made in
TensorFlow are written in C and C++. Broadly utilized Google items like
Google Photos and Google Voice Search are constructed utilizing
TensorFlow. The library has a convoluted front-end for Python. The Python
code will get accumulated and, after that, executed on TensorFlow conveyed
execution motor.
Special Features:
● Allows preparing various neural systems and numerous GPUs,
making models exceptionally productive for enormous scale
frameworks
● Easily trainable on CPU and GPU for disseminated figuring
● Flexibility in its operability, which means TensorFlow offers the
choice of taking out the parts that you need and leaving what you
don't
● Great level of network and designer support
● Unlike other information science Python libraries, TensorFlow
improves the way toward imagining every single piece of the
diagram.
● Keras
It is recognized as one of the coolest AI (Algorithm) Python libraries; Keras
offers a simpler tool for communicating neural systems. It additionally
features extraordinary utilities for accumulating models, preparing datasets,
imagining charts, and significantly more. Written in Python, Keras can keep
running over CNTK, TensorFlow, and Theano. The Python AI library is
created with an essential spotlight on permitting quick experimentation. All
Keras models are compact.
Contrasted with other Python AI libraries, Keras is moderate. This is because
of the way that it makes a computational diagram utilizing the backend
framework first and, after that, uses the equivalent to perform activities.
Keras is extremely expressive and adaptable for doing creative research.
Special Features:
● Being totally Python-based makes it simpler to troubleshoot and
investigate
● Modular in nature.
● Neural system models can be joined for growing increasingly
complex models
● Runs easily on both CPU and GPU
● Supports practically all models of a neural system, including
convolutional, inserting, completely associated, Pooling, and
repetitive.
● Seaborn
Fundamentally an information perception library for Python, Seaborn, is
based over the Matplotlib library. Additionally, it is firmly incorporated with
Pandas information structures. The Python information perception library
offers an abnormal state interface for drawing appealing just as useful factual
charts.
The primary point of Seaborn is to make representation an imperative piece
of investigating and getting information. Its dataset-arranged plotting
capacities work on exhibits and information edges containing entire datasets.
The library is perfect for inspecting connections among numerous factors.
Seaborn inside makes all the significant semantic mapping and measurable
collection for creating educational plots. The Python information
representation library additionally has devices for picking among shading
palettes that guide in uncovering designs in a dataset.
Special Features:
● Automatic estimation just as the plotting of direct relapse models.
● Comfortable perspectives on the general structure of complex
datasets.
● Eases building complex representations utilizing abnormal state
deliberations for organizing multi-plot matrices.
● Options for picturing bivariate or univariate disseminations.
● Specialized support for utilizing clear cut factors.
Special Features:
● Comes with a linguistic structure tagger
● Supports lexical assessment
Chapter 11: Future of Python
● Cross-Platform Language
One more of the best include about Python is that it is very various with
regards to the working framework. In straightforward words, Python can be
utilized for a working framework; for example, Linus, Windows, Ubuntu,
and so forth.
Thus, one can undoubtedly keep running off a product without agonizing
over framework support. It very well may be translated into the language
with the assistance of a convenient component that makes it gainful to utilize.
To sum things up, compose code on the Mac stage and run it easily on
Windows also.
Since the highlights and motivations to utilize Python are clear, give us a
chance to push ahead to the eventual fate of Python. There is no uncertainty
that Python has figured out how to beat different dialects that are taking it to
the top.
Subsequently, it has a wide arrangement of chances that can be taken into
consideration in the future. In the event that anything, it has expanded with
time and has gone over 45% in only a couple of years. There are quantities of
organizations that are subject to python developers to upgrade client
experience.
Tony Chan.
References
● Tutorials - Javatpoint. (n.d.). Retrieved from
https://www.javatpoint.com/
● Lutz, M. (2007). Learning Python. Farnham: OReilly.
● Lutz, M. (2009). Python Pocket Reference. Sebastopol: OReilly Media,
Inc.
● Slatkin, B. (2015). Effective Python: 59 specific ways to write better
Python. Upper Saddle River, NJ: Addison-Wesley.
● VanderPlas, J. (n.d.). A Quick Tour of Python Language Syntax.
Retrieved from https://jakevdp.github.io/WhirlwindTourOfPython/02-
basic-python-syntax.html
● 7. Simple statements. (n.d.). Retrieved from
https://docs.python.org/3/reference/simple_stmts.html
● Matthes, E. (2015). Python crash course: a hands-on, project-based
introduction to programming. San Francisco: No Starch Press.
● Pestunov, A., & Perov, A. (2017). E-learning course “Programming
Languages.” A Course of Lectures "Teaching Skills in Information and
Educational Environment of the University". doi:
10.12731/ofernio.2017.23146
● Shukla, X. U., & Parmar, D. J. (2016). Python – A comprehensive yet
free programming language for statisticians. Journal of Statistics and
Management Systems, 19(2), 277–284. doi:
10.1080/09720510.2015.1103446
● Hetland, M. L. (2014). Python Algorithms Mastering Basic Algorithms
in the Python Language. Berkeley, CA: Apress.