0% found this document useful (0 votes)
79 views

Python For Beginners - The Crash - Aaron Khan

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
79 views

Python For Beginners - The Crash - Aaron Khan

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 83

PYTHON FOR BEGINNERS

THE CRASH COURSE TO LEARN


PYTHON PROGRAMMING IN 3-DAYS (OR
LESS).
MASTER ARTIFICIAL INTELLIGENCE FOR
DATA
SCIENCE AND MACHINE LEARNING +
PRACTICAL
EXERCISES
Table of Contents
Introduction:
Chapter 1: What is Python
Chapter 2: Why Python is the Easiest Language to Learn
Chapter 3: Installing the Interpreter
Chapter 4: Using the Python Shell, IDLE and Writing the First Program
Chapter 5: Variables and Operators
Chapter 6: Data Types in Python
Chapter 7: Making your program Interactive
Chapter 8: Making Choices and Decisions
Chapter 9: Functions and Models
Chapter 10: How to Work with Files
Chapter 11: Object Oriented Programming
Chapter 12: Math and binary
Chapter 13: Exercises
Conclusion
© Copyright 2020 by Aaron Cox - All rights reserved.
This eBook is provided with the sole purpose of providing relevant information on a specific topic for
which every reasonable effort has been made to ensure that it is both accurate and reasonable.
Nevertheless, by purchasing this eBook, you consent to the fact that the author, as well as the publisher,
are in no way experts on the topics contained herein, regardless of any claims as such that may be made
within. As such, any suggestions or recommendations that are made within are done so purely for
entertainment value. It is recommended that you always consult a professional before undertaking any
of the advice or techniques discussed within.
This is a legally binding declaration that is considered both valid and fair by both the Committee of
Publishers Association and the American Bar Association and should be considered as legally binding
within the United States.
The reproduction, transmission, and duplication of any of the content found herein, including any
specific or extended information, will be done as an illegal act regardless of the end form the
information ultimately takes. This includes copied versions of the work, both physical, digital, and
audio, unless express consent of the Publisher is provided beforehand. Any additional rights reserved.
Furthermore, the information that can be found within the pages described forthwith shall be considered
both accurate and truthful when it comes to the recounting of facts. As such, any use, correct or
incorrect, of the provided information will render the Publisher free of responsibility as to the actions
taken outside of their direct purview. Regardless, there are zero scenarios where the original author or
the Publisher can be deemed liable in any fashion for any damages or hardships that may result from
any of the information discussed herein.
Additionally, the information in the following pages is intended only for informational purposes and
should thus be thought of as universal. As befitting its nature, it is presented without assurance
regarding its continued validity or interim quality. Trademarks that are mentioned are done without
written consent and can in no way be considered an endorsement from the trademark holder.
Introduction:
Programming has come a long way. The world of programming may have
started quite some time ago; it was only a couple of decades ago that it gained
attention from computer experts from across the globe. This sudden shift saw
some great minds who contributed to the entire age of programming far more
significant than most. We saw the great GNU project take shape during this
era. We came across the rather brilliant Linux. New programming languages
were born as well, and people certainly enjoyed these to the utmost.
While most of these programming languages worked, there was something
that was missing. Surely, something could be done to make coding a less
tedious task to do and carry out. That is precisely what a revolutionary new
language, named after Monty Python’s Flying Circus, did for the world.
Immediately, coding became so much easier for programmers. The use of this
language started gaining momentum, and today, it is set to overtake the only
language that stands before it to claim the prestigious spot of being the
world’s most favored language.
This language was the brainchild of Guido Van Rossum. Created in the year
1991, Python has become a byword for efficient and user-friendly
programming. This language is what connected the dots and gave
programmers the much-needed ease of coding that they have since been
yearning for. Naturally, the language was received well by the programming
community. Today, it is one of the most critical languages for both
professionals and students who aim to excel in fields like Machine Learning,
automation, artificial intelligence, and so much more.
With real-life examples showing a wide variety of use, Python is now living
and breathing in almost every major social platform, web application, and
website. All of this sounds interesting and exciting at the same time, but what
if you have no prior knowledge about programming? What if you have no
understanding of basic concepts and you wish to learn Python?
I am happy to report that this will provide you with every possible chance of
learning Python and allow you to jump-start your journey into the world of
programming. This is ideally meant for people who have zero understanding
of programming and may have never coded a single line of program before.
I will walk you through all the basic steps from installation to application.
We will look into various aspects of the language and hopefully provide you
with real-life examples to further explain the importance of such aspects. The
idea of this is to prepare you as you learn the core concepts of Python. After
this, you should have no problem choosing your path ahead. The basics will
always remain the same, and this ensures that each one of those basic
elements is covered in the most productive way possible. I will try to keep the
learning process as fun as I can without deviating from the learning itself.
Things You Need!
“Wait. Did you not say I don’t need to know anything about programming?”
Well, yes! You do not have to worry about programming or their concepts at
the moment, and when the time comes, I will do my best to explain those.
What is needed of you is something a little more obvious.

Computer: Like I said, obvious! You need a machine of your own


to download and practice the material and matter you learn from
here. To make the most out of the this, practice as you read. This
greatly increases your confidence and allows you to keep a steady
pace. The specifications do not matter much. Most of the modern
machines (2012 and above) should be able to run each of the
components without posing any problem.
An internet connection: You will be required to download a few
files from the internet.
An Integrated Development Environment (IDE): If, for some
reason, you felt intimidated by this terminology, relax! I will be
guiding you through each and every step to ensure you have all of
these and know what they are all about. For now, just imagine this
as a text editor.
A fresh mind: There is no point in learning if your mind is not
there with you. Be fresh, be comfortable. This may take a little
practice and a little time, but it will all be worth it.
That is quite literally all that you need. Before we go on into our very first
and start learning the essentials, there is but one more thing I would like to
clarify right away.
If you picked up a copy of this or are considering it, under the impression that
it will teach you all the basics about Python, good choice! However, if you
are of the idea that by the end of this, you will turn out to be a fully trained
professional with an understanding of things like machine learning and other
advanced Python fields, please understand that this would fall outside the
scope.
This is to serve as a guide, a crash course of a sort. To learn more advanced
methods and skills, you will first need to establish command over all the
basic elements and components of the language. Once done, it is highly
recommended to seek out that are for advanced learning.
What I can recommend you to do is to continue practicing your codes after
you have completed. Unlike driving and swimming, which you will
remember for the rest of your life, even if you stop doing them, Python
continues to update itself. It is essential that you keep yourself in practice and
continue to code small programs like simple calculator, number predictors,
and so on. There are quite a few exercises you can come across online.
For advanced courses, refer to Udemy. It is one of the finest sources to gain
access to some exceptional courses and learn new dimensions of
programming, amongst many other fields.
Phew! Now that this is out of the way, I shall give you a minute to flex your
muscles, adjust your seat, have a glass of water; we are ready to begin our
journey into the world of Python.
Chapter 1: What is Python
Python is a multi-purpose language created by Guido van Rossum. The
language boasts of a simple syntax that makes it easy for a new learner to
understand and use. This will introduce the basics of the Python language.
Stay tuned.
Let’s get started!
Python is described as a general-purpose language. It has many applications
and therefore, you can use it to accomplish many different functions.
The syntax of a python language is clean and the length of the code is short.
Developers who have used Python at one point of their lives will express how
fun it was to code with Python. The beauty of Python is that it offers you a
chance to think more about the task at hand instead of the language syntax.
Some history of Python
The design of the Python language started back in the 1980s and it was first
launched in February 1991.
Why was Python developed?
The reason why Guido Van Rossum embarked on the move to design a new
programming language is that he wanted a language that could offer a simple
syntax just like the ABC. This motivation led to the development of a new
language named Python.
But you may be wondering why just the name Python?
First, this language wasn’t named after the huge snake called python. No!
One of the interests of Rossum was watching comedy. He was a great fan of
the comedy series in the late seventies. As a result, the name of the language
was borrowed from the “Monty Python’s Flying Circus.”
Properties of Python
Easy to learn – The syntax of Python is simple and beautiful. Additionally,
Python programmers enjoy writing its syntax than other languages. Python
simplifies the art of programming and allows the developer to concentrate on
the solution instead of the syntax. For a newbie, this is a great choice to start
your Python career.
Portability – When it comes to Python portability, it offers you the ability to
run Python on different platforms without making any changes.
Python is described as a high-level language – In other words, you don’t need
to be scared of tedious tasks such as memory management and so on.
Alternatively, whenever you execute a Python code, it will automatically
change the language to a language that your computer understands. No need
to be worried about any lower-level operations.
Object-oriented – Since it is an object-oriented language, it will allow you to
compute solutions for the most difficult problems. Object-Oriented
Programming makes it possible to divide a large problem into smaller parts
by building objects.
Has a huge standard library to compute common tasks – Python has different
standard libraries for the programmer to use. As a result, you will not write
all the lines of code yourself. Instead, you will only import the library of the
relevant code.
A Brief Application of Python
Web Applications
You develop a scalable Web application using CMS and frameworks that are
created on Python. Popular environments for developing web applications
include Pyramid, Django, Django CMS, and Phone.
Other popular websites like Instagram, Mozilla, and Reddit are written in
Python language.
Scientific and Numeric Calculations
There are different Python libraries designed for Scientific and numeric
calculations. Libraries such as NumPy and SciPy use Python for general
computing purpose. And, there are specially designed libraries like AstroPy
for Astronomy, and so on.
Additionally, the Python language is highly applied in data mining, machine
learning, and deep learning.
A great Language for Tech Programmers
The Python language is an important tool used to demonstrate programming
to newbies and children. It is a great language that has important capabilities
and features. However, it is one of the easiest languages to learn because it
has a simple syntax.
Building Software Prototypes
Compared to Java and C++, Python is a bit slow. It may not be a great choice
when resources are restricted and efficiency is made compulsory.
But Python is a powerful language to build prototypes. For instance: You can
apply the Pygame library to develop the prototype of your game first. If you
enjoy the prototype, you can decide to use C++ to develop the actual game.
Chapter 2: Why Python is the Easiest Language to
Learn
Python is an interpretive, object-oriented and dynamic data type high-level
programming language. Since the birth of Python language in the early
1990s, it has gradually been widely used in processing system management
tasks and Web programming. Especially with the continuous development of
artificial intelligence, Python has become one of the most popular
programming languages.
The first benefit that you will notice with the Python language is that it is
easy to learn. This language was developed with the beginner in mind, in the
hopes of bringing more people into coding. Some of the traditional languages
were hard and bulky, and unless you were really passionate about some of the
work that you were doing with coding, you would probably decide to give up
long before anything was done. But with the Python language, things are a bit
different. This language as designed to be easy to learn and easy to read,
which helped make it possible for more people to get into the world of
coding.
Even though you will be pleasantly surprised by how easy it is to learn about
the Python language, you will also find that it is a powerful language. Don’t
let the simplicity of this language fool you; it has enough power to get the
work done, no matter how complex or hard the problem is. Even though
Python is able to handle some of the basic coding needs that you have, it also
has the power to help you to do things like machine learning and data
analysis. And if you have spent any time working with these topics, and these
ideas, you know that they are not easy.
With this in mind, Python is also going to have a lot of extensions and
libraries that help it to work better. This is primarily how you will be able to
get Python to work with some of those more complex tasks. You can add
these simply by installing them to your computer or system, and the Python
language is ready to go when you are. You can then handle algorithms, finish
your data analysis, and so much more. There are many Python data science
libraries available based on which step of the process you are working on at
the time
Why is Python special?
There are hundreds of programming languages now available for
programmers to start with. However, according to statistics from a survey
done by Harvard computer scientists Python is a leading language among
beginners. We will discuss about some of the reasons that make Python an
understandable language for new programmers.
Python has the following major advantages over other programming
languages:
(1) The grammar is concise and clear, and the code is highly readable.
Python's syntax requires mandatory indentation, which is used to reflect the
logical relationship between statements and significantly improve the
readability of the program.
(2) Because it is simple and clear, it is also a programming language with
high development efficiency.
(3) Python can be truly cross-platform, for example, the programs we develop
can run on Windows, Linux, macOS systems. This is its portability
advantage.
(4) It consists of A large number of rich libraries or extensions. Python is
often nicknamed glue language. It can easily connect various modules written
in other languages, especially C/C++. Using these abundant third-party
libraries, we can easily develop our applications.
(5) The amount of code is small, which improves the software quality to a
certain extent. Since the amount of code written in Python is much smaller
than that in other languages, the probability of errors is much smaller, which
improves the quality of the software written to a certain extent.
Python is very versatile and can be used in the following areas:
(1) web page development;
(2) Visual (GUI) interface development;
(3) Network (can be used for network programming);
(4) System programming;
(5) Data analysis;
(6) Machine learning (Python has various libraries to support it);
(7) Web crawlers (such as those used by Google);
(8) Scientific calculation (Python is used in many aspects of the scientific
calculation).
For example, Python is used in many Google services. YouTube is also
implemented in Python. The basic framework of the Wikipedia Network
initially is also implemented in Python.
How does python work?
Python Program Execution Principle is very simple. We all know that
programs written in compiled languages such as C/C++ need to be converted
from source files to machine languages used by computers, and then binary
executable files are formed after linking by linkers. When running the
program, you can load the binary program from the hard disk into memory
and run it.
However, for Python, Python source code does not need to be compiled into
binary code. It can run programs directly from the source code. The Python
interpreter converts the source code into bytecode and then forwards the
compiled bytecode to the Python virtual machine (PVM) for execution.
When we run the Python program, the Python interpreter performs two steps.
(1) Compiles Source Code into Byte Code
Compiled bytecode is a Python-specific expression. It is not a binary machine
code and needs further compilation before it can be executed by the machine.
This is also why Python code cannot run as fast as C/C++.
If the Python process has to write permission on the machine, it will save the
bytecode of the program as a file with the extension .pyc. If Python cannot
write the bytecode on the machine, the bytecode will be generated in memory
and automatically discarded at the end of the program. When building a
program, it is best to give Python permission to write on the computer, so as
long as the source code is unchanged, the generated .py file can be reused to
improve the execution efficiency.
(2) Forwarding the compiled bytecode to Python Virtual Machine (PVM) for
execution.
PVM is short for Python Virtual Machine. It is Python's running engine and
part of the Python system. It is a large loop that iteratively runs bytecode
instructions, completing operations one after another.
In this process, every python program is executed and gives results that can
be further analyzed and tested to deploy as new applications completely.
Chapter 3: Installing the Interpreter
Python has many free IDEs and environments available online. With this
variety of options, there are some programs which are better than others.
With their shortfalls in mind, the best software one can use to practice their
Python programming is PyCharm Community Edition.
Python is a common programming language for application development.
Python design focuses on code readability and clear programming for both
small and big projects. You are able to run modules and full application from
a massive library of resources on the server. Python works on various
operating systems, such as Windows. Installing Python on the Windows
server is a straightforward process of downloading the installer, and running
it on your server and configuring some adjustments can Python easier.
It is this software that I recommend to many of my students, although
Anaconda is another, I found quite useful. PyCharm won’t offer you the
extraordinary power and capabilities as professional software will, but for
beginners, it’s more than adequate.
With that in mind, we need only to download and install the software. I will
go through this process with you, step-by-step with pictures.
Step 1: Open your preferred internet browser, (Google Chrome, Firefox, etc.),
and search ‘PyCharm community edition’. You should see page-link depicted
in image 1.2 as your first result.
1.1: Searching PyCharm Community Edition

1.2: First Result for PyCharm Community Edition


Step 2: Once you click on the link, you should see a page like the one
depicted in image 2.1. From here, you can decide which version of PyCharm
you wish to download. Be it Mac, Windows or Linux for your OS, Pro or
Community edition depending on your preferred plan.
NOTE: I will be using Community Edition throughout
2.1: PyCharm Download Page
Step 3: Once you have chosen your preferred OS and version of PyCharm,
click the ‘Download’ button. You should see the PyCharm installer
downloading at the bottom-left of your screen.
3.1: PyCharm Downloading

Step 4: Once the download is


complete, click on the same box at the bottom-left of your screen. If you no
longer see the box or have closed your browser, locate the downloaded
installer in your Downloads folder. Double-click the icon to start the
installation.
4.1: PyCharm Download Finished

4.2: PyCharm Installer in Downloads Folder


Step 5: Now, we begin the installation. The process is simple, as you need
only click ‘Next’ and then ‘Install’ at the bottom of the installation process
boxes. However, I will be going through each box.
5.1: Box 1 - Introduction

This first box is simply introducing you to the installation process.


Click ‘Next’ to continue.
5.2: Box 2 - Install Location
The second box is concerning where the software will be installed. PyCharm
is a relatively small program, requiring less than 1GB of space. In addition to
that, you may want to install PyCharm in a certain folder, by clicking
‘Browse...’ you will be presented with an interface that allows you to select
which one.
RECOMMENDED: The default location is perfectly fine and should cause
no issues, as long as you have enough space for the program on your system.
I recommend you leave this option unaltered. Click ‘Next’ to continue.
5.3: Box 3 - Additional Installation Options
This step is purely optional, but I do recommend you create a Desktop
Shortcut by checking the box for ‘64-bit Launcher’, for ease of use. What this
will do is place an icon on your desktop, which you can use to quickly start
PyCharm without having to search for it in the Start Menu.
Whether you have selected this option or not, click ‘Next’ to continue.
5.4: Box 4 - Start Menu Folder Selection
This step is similar to 5.2, as you can select the folder where the software is
installed, but in this case, it is the Start Menu folder. If you have enabled the
Desktop Shortcut as recommended in 5.3, this step can be left without
alteration.
However, if you want the application icon to be stored in a specific folder,
you can change that here.
RECOMMENDED: Once more, the default location is perfectly fine and I
recommend you leave it unaltered.
Click ‘Install’ to continue.
5.5: Box 5 - PyCharm Installing
PyCharm is installing and you are on your way to Python programming!
Leave your computer running until the installation is complete.
5.6: Box 6 - PyCharm Finished Installing
PyCharm has been installed on your system and you have one more option
before clicking ‘Finish’. You can choose to run PyCharm now.
If you have unchecked this box and enabled the Desktop Shortcut, you can
find the following icon on your Desktop to start PyCharm.
5.7: PyCharm Desktop Shortcut Icon

Step 6: Once you have started PyCharm up, you should see the following as
depicted in image 6.1. For the first startup, PyCharm asks you to accept
standard terms & conditions before you can use the program.
You can read through these or not, but in order to continue, check the box
that states you have read and accepted the terms of this user agreement. Once
checked, click ‘Continue’.
6.1: Accepting User Agreement
Step 7: The box you should see is an option for most programming software.
The software developers ask if you allow the software to send data on your
usage to help in bug-fixing etc. For more details, they allow you an option to
read more about it.
You can choose to provide this information or not, you still have full access
to PyCharm.
7.1: Data Sharing Agreement
Step 8: We are in the final stages of this installation process. The few steps
are more preference steps than anything else. Once completed, you are ready
to move, where we will create a project for coding in.
Choose a theme for your UI. I will be using Darcula, but you can use
whichever. Once selected, click ‘Next: Featured plugins.
8.1: Theme Choosing
8.2: Featured Plugins
Once more, these are preference options. These plugins are more for the
experienced program and all are optional.
I won’t be using any additional plugins, so once you are ready, click ‘Start
Using PyCharm’
8.3: Finished and Ready to Start Creating Projects!
With that, you have finished installing and setting up PyCharm!
If you see the image in 8.3, you are ready to start where we will create a
project. An important last step before we start learning some code!
Chapter 4: Using the Python Shell, IDLE and
Writing the First Program
Once you have Python in your operating system, the following step is to
compile and run a program with Python.
A program is a series of instructions that have been coded and that will allow
you to perform a series of specific tasks on your computer. These coded
instructions are what are known as source code; these codes are what the user
or programmer sets in his computer.
The source code is written in the Python programming language and this
language will be converted into an executable file and for this to happen, in
other words, for the source code to be converted into an executable file, the
help of a compiler will be necessary that will be executed in a "central
processing unit" (CPU) and all this will happen with the help of an
interpreter.
In summary, we have that a compiler is going to convert our source code into
an executable file since it is a translator that transforms a program or source
code into a machine language so that it can be executed; this translation
process is what is known as compiling.
There is a difference between a compiler and an interpreter since the first one
translates a program described by the programming language into the
machine code of the system, while the interpreters only perform the
translation, be it instruction by instruction, and also do not store the result of
this translation.
Therefore, we have a source code that is going to be executable in two ways
by either a compiler or an interpreter who will execute it immediately.
When we open the IDLE in our system, in the same way that we did it before,
we are going to observe the screen that we find when we open our IDLE,
which is called Shell, or we can also call it as the interpreter of our Python
language.
Every time we open our interpreter or Shell, we will always find a kind of
header, which will always be the same, where it has Python information, such
as the version in which it is working, date and time, for example. This type of
format helps us appreciate that we are working with the Shell interpreter.
By means of this example, we will be able to visualize how our Shell
interpreter is doing the translation from Python language to machine
language instruction by instruction.
The default on OS X is that Python 3 is not going to be installed at all. If you
want to use Python 3, you can install it using some of the installers that are on
Python.org. This is a good place to go because it will install everything that
you need to write and execute your codes with Python. It will have the
Python shell, the IDLE development tools, and the interpreter. Unlike what
happens with Python 2.X, these tools are installed as a standard application in
the Applications folder.
You have to make sure that you are able to run both the Python IDLE and the
Python shell on any computer that you are using. And being able to run these
can be dependent on which version you have chosen for your system as well.
You will need to go through and check on your system which version of
Python is there before proceeding and then moves on from there to determine
which IDLE and shell you need to work with.
We write a line of codes in Python, starting with the very famous phrase in
Python for every beginner "Hello World" and we will do it in the following
way:
The syntax is written as follows:

Already written the


instruction that we want the program to execute, we only have to press the
"Enter" key and automatically the interpreter will translate instruction by
instruction and will not wait to receive another additional instruction but
executes once we press the "Enter" key.
Additional detail of the interpreter is that it can also be used from the
command prompt, which is also available on Windows, Linux and Mac.
In order to use the interpreter from the command prompt, simply type in the
word Python and press the "Enter" key. This way, you start to run the Python
interpreter and we know that we are effectively in the interpreter because, we
are going to see the same header as we saw before.
Now we can start to execute instructions written with Python:
--- print ("Hello world"), the interpreter is going to translate this line and
immediately shows us the result "Hello world".
Chapter 5: Variables and Operators
What are Variables?
A variable is nothing more than a reserved location in the memory, a
container if you like, where values are stored. The basic rules relating to
variables are:

Values can be strings, numeric or another data type


A variable is created when they are first assigned
A variable need to be assigned before you can reference it
The value that you store in the variable may be updated or
accessed at a far ahead time
Variables do not require a declaration
The variable data type, for example, float, int, string, etc., will be
decided by Python
The Python interpreter will allocate the required amount of
memory based on the variable data type

Naming Rules for Variables


Like many things in Python, variables come under strict naming conventions:

A variable must start with an underscore (_) or a letter – A to Z or


a to z
The other characters in the name may be underscores, letters or
numbers
Variables are case sensitive. For example, myname is a different
variable to MyName
Variable names can be any length within reason
Reserved keywords cannot be used – a list of these can be found
below

Basic Operators and Assignment Operators


The control flow of a program is the order that the code is executed in and
this is regulated through loops, conditional statements and function calls. We
are going to look first at Boolean and comparison operators, followed by the
if statement and all the variations of it.
Booleans and Comparison Operators
Boolean data types may be True or they may be False, nothing else. Booleans
are used to control program flow and to make comparisons. They are
representative of truth values that we associate with mathematics, the logic
side of it to be precise. Booleans were named after George Boole, a
mathematician, and the word always starts with a capital B. By the same
token, the two values, True and False, also start with capital letters. The
reason for this is because, in Python, they are special values.
We are going to look at how these Booleans work, including comparison
operators, and logical operators. First, we look at the comparison operators.
Comparison Operators
In computer programming, we use comparison operators as a way of
comparing two or more values and to evaluate a single value, the Boolean
True or False. These are the comparison operators:
OperatorDescription
==is equal to
! =is not equal to
<is less or lower than
>is greater or larger than
<=is less or equal to
>=is greater or equal to
To better understand the way they work, let’s look at an example where we
assigned two variables with integer values:
x=7
y=9
We can see from the example that, because x has been assigned a value of 7,
it is greater than variable y, which has been assigned 9 as a value.
Using these variables and the values that go with them, we can take a better
look at the comparison operators. We are going to write a program that asks
whether each of the operators will evaluate to True or to False and then print
the result. To help understand it even more, we will ask for a string to be
printed that shows us what is happening.
x=7
y=9
print ("x == y:", x == y)
print ("x! = y:", x! = y)
print ("x < y:", x < y)
print ("x > y:", x > y)
print ("x <= y:", x <= y)
print ("x >= y:", x >= y)
The output would be:
x == y: False
x! = y: True
x < y: True
x > y: False
x <= y: True
x >= y: False
If we followed the logic in Math, we can see that Python evaluated each of
these expressions as:
Is 7 (x) equal to 9 (y)? False
Is 7 not equal to 9? True
Is 7 less than 9? True
Is 7 greater than 9 False
Is 7 less than or equal to 9? True
Is 7 not less than or equal to 9? False
We used integer numbers for this example but we could just have easily used
floats. We can also use strings with Boolean operators but do remember that
they are case sensitive. Look at a practical example of how strings are
compared:
Sally = "Sally"
sally = "sally"
print ("Sally == sally: ", Sally == sally)
The output would be:
Sally == sally: False
The string called “Sally” is not the same as the string called “sally” because
they are not the same – one begins with a capital letter, the other doesn’t. If
we were to add in a variable that we assigned with a value, “Sally”, they
would evaluate as equal:
Sally = "Sally"
sally = "sally"
also_Sally = "Sally"
print ("Sally == sally: ", Sally == sally)
print ("Sally == also_Sally", Sally == also_Sally)
The output would be:
Sally == sally: False
Sally == also_Sally: True
As well as these, we can use two other comparison operators, < and >, to
compare strings as well as evaluating Booleans with these operators:
t = True
f = False
print ("t! = f: ", t! = f)
Output
t! = f: True
This has resulted in an evaluation that True does not equal False.
Note that there is a difference between these two operators - = and ==:
x = y # Sets x as equal to y
x == y # Evaluates if x is equal to y
The first one, =, is called an assignment operator. This will set a value as
being equal to another value. ==, on the other hand, is a comparison operator
and this evaluates if two separate values are equals.
Logical Operators
We can make sue of three different logical operators when we want to
compare two values. These will evaluate an expression, down to True or
False, both Boolean values. Here is what those operators are and what they
do:
OperatorDescription
andEvaluates True if both values are true
orEvaluates True if one or more values is true
not evaluates True only if the evaluation is false
We use the logical operators to determine if at least two expressions are true
or not. For example, we can use a logical operator to see if a specific grade is
a passing grade and to check that a specific student has been registered in the
course. If both are True, the student is assigned with a grade. Another way of
looking at this would be to see if a user is an active and valid user at an
online store and this would be based on whether they have made any
purchases within the last 3 months or if they have been extended store credit.
To better understand logical operators, look at the following expressions:
print ((9 > 7) and (1 < 3)) # Both of the original expressions evaluate to True
print ((7 == 7) or (4! = 4)) # One of the original expressions evaluates to True
print (not (4 <= 2)) # The original expression evaluates to False
The output would be:
True
True
True
Let’s break this down:
In the first expression, print ((9 > 7) and (1 < 3)), both 9 > 7 and 1 < 3 had to
evaluate as True because we used the and operator and both of the statements
are true
In the second expression, print ((7 == 7) or (4! = 4)), because 7 ==
7 evaluates to True, it doesn’t matter that (4! = 4) evaluated to False. We used
the or operator so only one of them had to evaluate True. If the and operator
had been used instead, this would have been False.
In the third expression, print (not (4 <= 2)), the use of the not operator means
that the False value that the expression returns is negated and the output is
True.
Now let’s look at some expressions where floating points are used instead of
integers – we want to see False as the evaluated Boolean value.
print ((-0.1 > 1.5) and (0.7 < 4.1)) # One of the original expressions evaluates
to False
print ((6.5 == 7.9) or (8.2! = 8.2)) # Both of the original expressions evaluate
to False
print (not (-4.7 <= 0.2)) # The original expression evaluates to True
In this example:
The and operator has to have one or more False expressions that evaluate to
False or both of the expressions has to evaluate as False
The inner expression of the not operator has to be True otherwise the new
expression cannot evaluate as False
Compound statements may also be written with the and, not and or operators:
not ((-0.1 > 1.5) and ((0.7 < 4.1) or (0.2 == 0.2)))
Now, let's take a look at the inner expression – (o.7 < 4.1) or (0.2 == 0.2).
This will evaluate as True because both of the statements are True in
mathematical terms.
Then, we take the value that was returned as True and add it to the following
inner expression – (0.1 > 1.5) and (True). This will evaluate as False because
the first statement is False and a False and True must always return False.
Lastly, the final expression – not (False) will evaluate as True so, if we were
to print all this out, the output would be:
True
Using Boolean Operators for Controlling Flow
To control how a program flows and what the outcome will be, we use low
control statements and these are made up of conditions and clauses.
A condition will evaluate to True or False and that gives us the point in the
program where a decision has been made. In other words, the condition will
determine if something will evaluate to True or to False.
The clause is a code block and it comes after the condition. The clause is
responsible for determining what the program outcome is. To clear it up, if
you had a construction of “if y is True, then do this”, the clause is the do part
of it. The example below shows you the control flow of a program through
the comparison operators working together with conditional statements.
if grade >= 70: # Condition
print ("Passing grade") # Clause
else:
print ("Failing grade")
The program is going to evaluate each grade from the students and evaluate if
they are a passing or a failing grade. If a student had a grade of 75, the initial
statement will evaluate as True and the Passing grade print statement is
triggered. If a student has a grade of 69, the initial statement evaluates as
False and the Failing grade print statement will be executed.
Chapter 6: Data Types in Python
The basic operations that can be done in Python, we now move on to a
discussion of data types. Computer programming languages have several
different methods of storing and interacting with data, and these different
methods of representation are the data types you’ll interact with. The primary
data types within Python are integers, floats, and strings. These data types are
stored in Python using different data structures: lists, tuples, and dictionaries.
We’ll get into data structures after we broach the topic of data types.
Integers
Integers in Python is not different from what you were taught in math class: a
whole number or a number that possess no decimal points or fractions.
Numbers like 4, 9, 39, -5, and 1215 are all integers. Integers can be stored in
variables just by using the assignment operator, as we have seen before.
Floats
Floats are numbers that possess decimal parts. This makes numbers like
-2.049, 12.78, 15.1, and 1.01 floats. The method of creating a float instance in
Python is the same as declaring an integer: just choose a name for the
variable and then use the assignment operator.
String
While we’ve mainly dealt with numbers so far, Python can also interpret and
manipulate text data. Text data is referred to as a “string,” and you can think
of it as the letters that are strung together in a word or series of words. To
create an instance of a string in Python, you can use either double quotes or
single quotes.
string_1 = "This is a string."
string_2 = ‘This is also a string.’
However, while either double or single quotes can be used, it is
recommended that you use double quotes when possible. This is because
there may be times you need to nest quotes within quotes, and using the
traditional format of single quotes within double quotes is the encouraged
standard.
Something to keep in mind when using strings is that numerical characters
surrounded by quotes are treated as a string and not as a number.
# The 97 here is a string
Stringy = "97"
# Here it is a number
Numerical = 97
Type Casting in Python
The term “type casting” refers to the act of converting data from one type to
another type. As you program, you may often find out that you need to
convert data between types. There are three helpful commands that Python
has which allow the quick and easy conversion between data types: int (),
float () and str ().
All three of the above commands convert what is placed within the
parenthesis to the data type outside the parentheses. This means that to
convert a float into an integer, you would write the following:
int (float here)
Because integers are whole numbers, anything after the decimal point in a
float is dropped when it is converted into an integer. (Ex. 3.9324 becomes 3,
4.12 becomes 4.) Note that you cannot convert a non-numerical string into an
integer, so typing: int (“convert this”) would throw an error.
The float () command can convert integers or certain strings into floats.
Providing either an integer or an integer in quotes (a string representation of
an integer) will convert the provided value into a float. Both 5 and “5”
become 5.0.
Finally, the str () function is responsible for the conversion of integers and
floats to strings. Plug any numerical value into the parenthesis and get back a
string representation of it.
List
Lists are just collections of data. When you think about a list in regular life,
you often think of a grocery list or to-do list. These lists are just collections of
items, and that’s precisely what lists in Python are; collections of items. Lists
are convenient because they offer quick and easy storage and retrieval of
items.
Let’s say we have a bunch of values that we need to access in our program.
We could declare separate variables for all those values, or we could store
them all in a single variable as a list. Declaring a list is as simple as using
brackets and separating objects in the list with commas. So, if we wanted to
declare a list of fruits, we could do that by doing the following:
Fruits = ["apple", "pear", "orange", "banana"]
It’s also possible to declare an empty list by just using empty brackets. You
can add items to the list with a specific function, the append function -
append (). We can access the items in the list individually by specifying the
position of the item that we want. Remember, Python is zero-based, and so to
get the first item is 0 in the list. How do we select the values from a list? We
just declare a variable that references that specific value and position:
Apple = fruits [ 0]
Tuple
Tuples are very similar to lists, but unlike lists, their contents cannot be
modified once they are created. The items that exist in the tuple when created
will exist for as long as the tuple exists. If it’s unclear as to when tuples
would be useful, they would be helpful whenever you have a list of items that
will never change. For example, consider the days of the week. A list
containing all the days of the week won’t change. In practice, you are likely
to use tuples far less often than you will use lists, but it’s good to be aware of
the existence of tuples.
Functionally, tuples are declared and accessed very similarly to lists. The
major difference is that when a list is created, parentheses are used instead of
brackets.
This_is_a_tuple = ("these", "are", "values", "in", "a", "tuple")
The items can be accessed with brackets, just like a list.
Word = this_is_a_tuple [ 0]
Dictionary
Dictionaries hold data that can be retrieved with reference items, or keys.
Dictionaries can be confusing for first-time programmers but try to imagine a
bank filled with a number of safety deposit boxes. There are rows and rows
of these boxes, and the contents of each box can only be accessed when the
correct key is provided. Much like opening a deposit box, the correct key
must be provided to retrieve the value within the dictionary. In other words,
dictionaries contain pairs of keys and the value that can be accessed with
those keys.
When you declare a dictionary, you must provide both the data and the key
that will point to that data. These key-value pairs must be unique. Evidently,
it would be a problem if one key could open multiple boxes, so keys in a
dictionary cannot be repeated; you cannot have two keys, both named
“Key1”.
The syntax for creating a key in Python is curly braces containing the key on
the left side and the value on the right side, separated by a colon. To
demonstrate, here’s an example of a dictionary:
Dict_example = {"key1": 39}
If you want to create a dictionary with multiple items, all you need to do is
separate the items with commas.
Dict_example2 = {"key1": 39, "key2": 21, "key3": 54}
Dictionaries can also be declared by using the dict () method. You could
create the same dictionary as above by-passing keys and their values using
the assignment operator and still separating them with commas.
Dict_example3 = duct (key1 = 39, key2 = 21, key3 = 54)
Note that this method uses parentheses instead of curly braces and doesn’t
use quotes.
To access items within the dictionary, you need to supply the appropriate
key. The syntax for this in Python is dictionary[‘key’], so in order to get 39
from the dictionary above, you would use this syntax:
number = Dict_example3["key1"]
Since the syntax above selects the value associated with the passed key, you
might be able to guess that we can overwrite the data by selecting the value
we want and using an assignment operator.
Dict_example3["key1"] = 99
Much like how it is possible to create an empty list with just an empty pair of
parentheses, we can also create an empty dictionary by using empty brackets
when we declare the dictionary.
Dict_example4 = {}
To add data to a dictionary, all we need to do is create a new dictionary entry
and assign a value to it.
Dict_example4["key1"] = 109
To drop values from the dictionary, we use the del command followed by the
dictionary and the key we want to drop.
del Dict_example4["key1"]
Chapter 7: Making your program Interactive
Input0
When writing your program or creating an application, you may require the
users to enter an input such as their username and other details. Python
provides the input () function that helps you get and process input from users.
Other than entering input, you may require the users to perform an action so
that they may go to the next step. For example, you may need them to press
the enter key on the keyboard to be taken to the next step.
Example:
input ("\n\n Press Enter key to Leave.")
Just type the above statement on the interactive Python interpreter then hit the
Enter key on the keyboard. You will be prompted to press the Enter key:
The program waits for an action from the user to proceed to the next step.
Notice the use of \n\n which is characters to create a new line. To create one
line, we use a single one, that is, \n. In this case, two blank lines will be
created. That is how Python input () function works.
Print ()
Python comes with many in-built functions. A good example of such a
function is the “print ()” function which we use for displaying the contents on
the screen. Despite this, it is possible for us to create our own functions in
Python. Such functions are referred to as the “user-defined functions”.
#!/usr/bin/python3
def functionExample():
print ('The function code to run')
bz = 10 + 23
print(bz)
Triple Quotes
Before we move into triple quotes, keep in mind that you can also create a
string like 'this'.
>>> 'this''this'
We can create the string, but we really don't have to do anything with it. The
interpreter will tell you what it is. Next enter the following into the
interpreter. (Enter 3 single quotes before and after). Warning a double quote
and single quote together will give a different error.
>>> '''line 1... line 2''''line 1\nline 2'
Notice the (\n) fora new line. Try it with print in front of it and it will put the
string in two separate lines.
>>> print ('''line 1 ... line 2''') line 1 line 2
If you enter '\n' it will display the following string on a new line..
>>> Print('I\ngo')I go
The results will be the same with '>>>'. Now a raw string with some slight
changes. Try it at the interpreter.
>>> r'string''string' >>> r'string\string2''string\\string2' >>> r"string\string2"
'string\\string2' >>> print("string\string2")string\string2 >>>
r"""string\string2""" 'string\\string2' >>> print(r"""string\string2""")
string\string2
The last example is to show that you can test your expressions as your scripts
progress towards complexity. The string examples above will become more
clear as you progress.
Escape characters
Have a look at the following code:

print(“\tHi there”)
output:
Hi there #tabbed to the right

So what is with the \t ?


The backslash ( \ ) character is used to escape characters that are required to
be interpreted differently by Python. Sounds a bit of a mouthful right!
Have another look at the output in the example above. Notice how the text
(Hi there) is tabbed to the right. Inserting the escape character \t at the
beginning of the string results in the string being tabbed to the right.
Adding two escape characters \t would result in the string being tabbed to the
right twice:

print ( "\t\tHi there")


output:
Hi there # tabbed to the right twice

\n is another popular escape character. \n adds a new line to the string.

print( "I’m going for a walk\nin the park\nbecause it is a lovely\n\tday")


output:
I’m going for a walk
in the park #adds new lines
because it is a lovely day
day #adds new line & a tab to the right

There is no space between the text and the escape character \thiya
Here are some of the most regularly used escape characters in Python.
Escape Description
character New Line
\n Horizontal
\t Tab
\\ Backslash
\’ Single quote
\” Double Quote
Let’s have a look at the some more escape characters.
The following sentences would result in an error when printed:

print ( "I said "hello mate" and he totally ignored me")


print (‘He said he’d be there at 2pm’)

In the first example Python thinks that the inverted comma before hello is the
end of the string. The third inverted comma would cause the program to
crash. Likewise, in the second sentence Python would take the back quote on
the word he’d to mean the end of the string and throw an error when it
encounters the third comma. One solution is to use single quotes when you
intend using inverted commas in the string:

print ( ‘I said “hello mate” and he totally ignored me’)

And use double quote if you intend using a lot of back quotes such as he’d,
there’s etc. in your string:

print ( " He said he’d be there at 2pm but there’s no sign of him")

Alternatively, you can use the escape character \

print ( "I said \"hello mate\" and he totally ignored me")


print ('He said he\'d be there at 2pm but there\'s no sign of him')
output:
I said "hello mate" and he totally ignored me
He said he'd be there at 2pm but there's no sign of him

Now what if you want just to print a backslash \ in Python? Yes, you also
must escape it.

print ("\") #will result in an error


print ("\\") #use a backslash to escape a backslash
output:
\

So how does this work in real life? Have a look at a snippet from a sample
food menu:
“Available drinks include tea\coffee\water”
To print this in we need to include the escape character \

print ("Available drinks include tea\\coffee\\water")


output:
Available drinks include tea\coffee\water
Chapter 8: Making Choices and Decisions
Conditions Statements
In some of the code samples we have used until now, you may notice that the
codes follow a pattern of execution that is religiously adhered to. One
prominent pattern is the top to bottom order of execution each of these codes
uses. Bringing that to light now, did you know it is possible to alter this order
of execution? Say, for instance, you want the program to make decisions on
its own, performing different actions depending on the situation that comes
up. Like printing, “Good Morning” or “Good Night” depending on the time
of day.
This is a possible feat in Python and can be achieved with the use of control
flow statements. These statements are three in number in Python, namely
while, if, and for statements. Let’s discuss each one of them briefly:
If Statements
The if statement serves as a means of taking control of how a statement that
follows it is executed — in this case, a block of code or single statement
contained in braces. The if statement evaluates the expression contained in
parentheses. Should the expression result in a value considered to be true, the
execution process is initiated? If not, the whole statement is abandoned.
Doing this allows your PHP script to make decisions on its own based on a
range of factors selected.
Syntax:
if ( expression ) {
// code to run if the expression outputs as true
}
Sample:
The following code would display x is greater than y if $x is greater than $y:
<?php
$x=5;
$y=2;
if ($x > $y)
echo "x is bigger than y";
?>
Inline If
This statement is used alongside the if…else statement during the execution
of a series of codes, should one of a variety of conditions be true. As the
name connotes, the elseif statement is a mixture of both if and else
statements. As with the else statement, the elseif statement extends the if
statement to run another statement in the event that the main if the expression
is evaluated as FALSE. Albeit, contrary to the else statement, the else if
statement runs the alternative expression only when the assigned conditional
expression is evaluated to be TRUE. So, put simply, whenever you wish to
run a set of code when one of many different conditions evaluate to true, the
else if statement should be used.
Syntax
if (condition)
code to be run if the condition evaluates to true;
elseif (condition)
code to be run if the condition evaluates to true;
else
code to be run if the condition evaluates to false;
Sample:
The sample shown below produces “Good morning. Rise and shine!” if the
period of the day is Morning, and “Good night! Sleep well.” when it is night.
Otherwise, it produces “Have a great day!”
<html>
<body>
<?php
$t = time("T");
if ($t == "Morn")
echo "Good morning. Rise and shine!";
elseif ($t == "Ngt")
echo "Good night! Sleep well.";
else
echo "Have a great day!";
?>
</body>
</html>
When executed, the result shown below will be outputted:
Good morning. Rise and shine!
While Loop
This type of loop runs a specific block of code for as long as the given
condition remains true. Once the given condition is no longer valid, or turns
to false, the block of code will end right away.
This is quite a useful feature as there may be codes that you may need to rely
on to process information quickly. To give you an idea, suppose, you are to
guess a number. You have three tries. You want the prompt to ask the user to
guess the number. Once the user guesses the wrong number, it will reduce the
maximum number of tries from three to two, inform the user that the number
is wrong and then ask to guess another time. This will continue until either
the user guesses the right number or the set number of guesses are utilized,
and the user fails to identify the number.
Imagine just how many times you would have to write the code over and over
again. Now, thanks to Python, we just type it once underneath the ‘while’
loop, and the rest is made for us.
Here’s how the syntax for the ‘while’ loop looks like:
while condition:
code
code

You begin by typing in the word ‘while’ followed by the condition. We then
add a colon, just like we did for the ‘if’ statement. This means, whatever will
follow afterward, it will be indented to show that the same is working
underneath the loop or the statement.
Let us create a simple example from this. We start by creating a variable.
Let’s give this variable a name and a value like so:
x=0
For Loop
In Python, the for…in statement is a looping statement that allows users to
iterate over a sequence of objects. That is, it is used to go through every item
that makes up a sequence. Take note that a sequence refers to an ordered set
of items. Let’s consider the same code sample used for the if statement. This
time, though, save the file by the name “for. py”:
for x in range(1, 7):
print(x)
else:
print(‘The for loop is complete)
Output:
$ python for. py
1
2
3
4
5
6
The for loop is completed
How the for statement Works:
In the code sample used above, we attempt to print out a sequence of
numbers. This sequence of numbers is generated with the help of a built-in
“range” function. What we do at this point is to enter two numbers into the
program, and the “range” function returns a sequence of numbers beginning
from the initial number up to the second one. For instance, range (1,7)
produces the sequence (1, 2, 3, 4, 5, 6). In a default state, range assumes a
step count of 1. If we add a third number into the range, then it automatically
takes the place of the default step count. Take, for instance, range (1,7,2)
produces the sequence [1,3,5]. Take note that the range reaches up to the
second number, but does not include the second number itself. So, the second
number serves as a boundary the range never reaches or exceeds. Keep in
mind that the range() function only generates one number per time. So, if you
need a full set of numbers at any point, use the list() on the range() function.
For instance:
list(range(7)) will result in the sequence [0, 1, 2, 3, 4, 5, 6].
Moving on, the for loop steps in and begins iteration over the range— for x in
range(1,7) is the same as for x in [1, 2, 3, 4, 5, 6]. This case is also similar to
assigning each object or number in the sequence to x, one per time, and then
running the clock of code for every value of x. At this point, we go straight to
printing the values within the block of code. Recall that the else of the code
remains optional. So, when it is introduced, it is only ever executed after the
for loop has been entirely executed, or until a break statement is used. Also,
recall that for in loops work on all sequences. At this point, there is a
sequence of numbers produced from executing the range function. However,
it is possible to use still any other sequence containing any type of object.
Break
The break statement in Python is applied as a breakout strategy from a loop
statement. That is, it is used to stop the running of a loop statement, even
when the condition for looping remains True, and the sequence of objects has
not undergone complete iteration. A point worth noting is that when you
apply the break statement to a while or for loop, any other alternative loop,
such as the else or elif block, remains unexecuted.
Let’s consider the same code sample used for the if statement. Save the file
by the name “break. py”:
while True:
m = input('Enter something : ')
if m == 'quit':
break
print('Length of the string is', len(m))
print('Completed')
When the code is executed, the result is as follows:
$ python break. py
Enter something: Python is easy to learn
Length of the string is 23
Enter something: When my work is over
Length of the string is 20
Enter something: You could make your work fun:
Length of the string is 29
Enter something: Hello, World!
Length of the string is 13
Enter something: quit
Completed
Continue
In Python, the continue statement is used to inform the program to skip the
remainder of the statements yet unexecuted in the present loop block and
continue to the following loop iteration. Let’s consider a sample code of the
continue statement in use. Save the file as continue. py.
while True:
j = input(‘Write something : ')
if j == 'quit':
break
if lensj) <5:
print(‘Entry is too small')
continue
print('Entry is of sufficient length')
# Process other type of things here...
When the code sample above is executed, the result is as follows:
$ python continue. py
Enter something: x
Entry is too small
Enter something: 515
Entry is too small
Write something: vwxyz
Entry is of sufficient length
Write something: quit
Try & Except
The try except blocks was used to manage the error. However, you or your
user can still do something to screw your solution up. For example:
>>> def div(dividend, divisor):
try:
print(dividend / divisor)
except:
print("Cannot Divide by Zero.")
>>> div(5, "a")
Cannot Divide by Zero.
>>> _
The statement prepared for the “except” block is not enough to justify the
error that was created by the input. Dividing a number by a string does not
warrant a “Cannot Divide by Zero.” message.
For this to work, you need to know more about how to use except block
properly. First of all, you can specify the error that it will capture and respond
to by indicating the exact exception. For example:
>>> def div(dividend, divisor):
try:
print(dividend / divisor)
except ZeroDivisionError:
print("Cannot Divide by Zero.")
>>> div(5, 0)
Cannot Divide by Zero.
>>> div(5, "a")
Traceback (most recent call last):
File "<stdin>", line 1, <module>
File "<stdin>", line 3, in div
TypeError: unsupported operand type(s) for /: 'int' and 'str'
>>> _
Chapter 9: Functions and Models
Functions of the regression analysis
Trend Forecasting
Determine the strength of predictors
Predict an effect
Breaking down regression
There are two basic states of regression-linear and multiple regression.
Although there are different methods for complex data and analysis. Linear
regression contains an independent variable to help forecast the outcome of a
dependent variable. On the other hand, multiple regression has two or more
independent variables to assist in predicting a result.
Regression is very useful to financial and investment institutions because it is
used to predict the sales of a particular product or company based on the sales
and GDP growth among many other factors. The capital pricing model is one
of the most common regression models applied in the finance. The example
below describes formulae used in the linear and multiple regression.

Choosing the best regression model


Selecting the right linear regression model can be very hard and confusing.
Trying to model it with a sample data cannot make it easier. These are some
of the most popular statistical methods which one can use to choose models,
challenges that you might come across, and lists some practical advice to use
to select the correct regression model.
It always begins with a researcher who would like to expand the relationship
between the response variable and predictors. The research team that is
accorded with the responsibility to perform investigation essentially measures
a lot of variables but only has a few in the model. The analysts will make
efforts to reduce the variables that are different and apply the ones which
have an accurate relationship. As time moves on, the analysts continue to add
more models.
Statistical methods to use to find the best regression model
If you want a great model in regression, then it is important to take into
consideration the type of variables which you want to test as well as other
variables which can affect the response.
Modified R-squared and Predicted R-squared.
Your model should have a higher modified and predicted R-squared values.
The statistics are shown below help eliminate critical issues which revolve
around R-squared.
• The adjusted R squared increases once a new term improves the model.
• Predicted R-squared belongs to the cross-validation that helps define how
your model can generalize remaining data sets.
P-values for the Predictors
When it comes to regression, a low value of P denotes statistically significant
terms. The term “Reducing the model” refers to the process of factoring in all
candidate predictors contained in a model.
Stepwise regression
This is an automated technique which can select important predictors found
in the exploratory stages of creating a model.
Real World Challenges
There are different statistical approaches for choosing the best model.
However, complications still exist.
• The best model happens when the variables are measured by the study.
• The sample data could be unusual because of the type of data collection
method. A false positive and false negative process happens when you handle
samples.
• If you deal with enough models, you’ll get variables that are significant but
only correlated by chance.
• P-values can be different depending on the specific terms found in the
model.
• Studies have discovered that the best subset regression and stepwise
regression can’t select the correct model.
Finding the correct Regression Model
Theory
Perform research done by other experts and reference it into your model. It is
important that before you start regression analysis, you should develop ideas
about the most significant variables. Developing something based on
outcome from other people eases the process of collecting data.
Complexity
You may think that complex problems need a complex model. Well, that is
not the case because studies show that even a simple model can provide an
accurate prediction. Once there is a model with the same explanatory
potential, the simplest model is likely to be a perfect choice. You just need to
start with a simple model as you slowly advance the complexity of the model.
How to calculate the accuracy of the predictive model
There are different ways in which you can compute the accuracy of your
model. Some of these methods include:
You divide the dataset into a test and training data set. Afterward, build the
model based on the training set and apply the test set as a holdout sample to
measure your trained model with the test data. The following thing to do is to
compare the predicted values using actual values by computing the error by
using measures like the “Mean Absolute Percent Error” (MAPE). If your
MAPE is less than 10%, then you have a great model.
2. Another method is to calculate the “Confusion Matrix” to the computer
False Positive Rate and False Negative Rate. These measures will allow a
person to choose whether to accept the model or not. If you consider the cost
of the errors, it becomes a critical stage of your decision whether to reject or
accept the model.
3. Computing Receiver Operating Characteristic Curve (ROC) or the Lift
Chart or Area under the curve (AUC) are other methods that you can use to
decide on whether to reject or accept a model.
Chapter 10: How to Work with Files
The succeeding thing that we need to focus on when it comes to working
with Python is making sure we know how to work and handle files. It may
happen that you are working with some data and you want to store them
while ensuring that they are accessible for you to pull up and use when they
are needed. You do have some choices in the way that you save the data, how
they are going to be found, and how they are going to react in your code.
When you work with the files, you will find that the data is going to be saved
on a disk, or you can re-use in the code over and over again as much as you
would like. This is going to help us learn a bit more about how to handle
some of the work that we need to do to ensure the files behave the way that
they should, and so much more.
Now, we are going to enter into file mode on the Python language, and this
allows you to do a few different options along the way. A good way to think
about this is that you can think about it like working on a file in Word. At
some point, you may try to save one of the documents that you are working
with so that it doesn’t get lost and you can find them. These kinds of files in
Python are going to be similar. But you won’t be saving pages as you did on
Word, you are going to save parts of your code.
You will find with this one that there are a few operations or methods that
you can choose when it comes to working with files. And some of these
options will include:
Closing up a file you are working on.
Creating a brand new file to work on.
Seeking out or moving a file that you have over to a new location to make it
easier to find.
Writing out a new part of the code on a file that was created earlier.
Creating new files
The first task that we are going to look at doing here is working on creating a
file. It is hard to do much of the other tasks if we don’t first have a file in
place to help us out. if you would like to be able to make a new file and then
add in some code into it, you first need to make sure the file is opened up
inside of your IDLE. Then you can choose the mode that you would like to
use when you write out your code.
When it comes to creating files on Python, you will find there are three
modes that you can work with. The three main modes that we are going to
focus on here include append (a), mode(x) and write(w).
Any time that you would like to open up a file and make some changes in it,
then you would want to use the write mode. This is the easiest out of the three
to work with. The write method is going to make it easier for you to get the
right parts of the code set up and working for you in the end.
The write function is going to be easy to use and will ensure that you can
make any additions and changes that you would like to the file. You can add
in the new information that you would like to the file, change what is there,
and so much more. If you would like to see what you can do with this part of
the code with the write method, then you will want to open up your compiler
and do the following code:
#file handling operations
#writing to a new file hello. txt
f = open(‘hello. txt’, ‘w’, encoding = ‘utf-8’)
f.write(“Hello Python Developers!”)
f.write(“Welcome to Python World”)
f.flush()
f.close()
From here, we need to discuss what you can do with the directories that we
are working with. The default directory is always going to be the current
directory. You can go through and switch up the directory where the code
information is stored. Still, you have to take the time, in the beginning, to
change that information up, or it isn’t going to end up in the directory that
you would like.
Whatever directory you spent your time in when working on the code is the
one you need to make your way back to when you want to find the file. If you
would like it to show up in a different directory, make sure that you move
over to that one before you save it and the code. With the option that we
wrote above, when you go to the current directory (or the directory that you
chose for this endeavor, then you will be able to open up the file and see the
message that you wrote out there.
For this one, we wrote a simple part of the code. You, of course, will be
writing out codes that are much more complicated as we go along. And with
those codes, there are going to be times when you would like to edit or
overwrite some of what is in that file. This is possible to do with Python, and
it just needs a small change to the syntax that you are writing out. A good
example of what you can do with this one includes:
#file handling operations
#writing to a new file hello. txt
f = open(‘hello. txt’, ‘w’, encoding = ‘utf-8’)
f.write(“Hello Python Developers!”)
f.write(“Welcome to Python World”)
mylist = [“Apple”, “Orange”, “Banana”]
#writelines() is used to write multiple lines into the file
f.write(mylist)
f.flush()
f.close()
The example above is a good one to use when you want to make a few
changes to a file that you worked on before because you just need to add in
one new line. This example wouldn’t need to use that third line because it just
has some simple words, but you can add in anything that you want to the
program, just use the syntax above and change it up for what you need.
What are the binary files?
One other thing that we need to focus on for a moment before moving on is
the idea of writing out some of your files and your data in the code as a
binary file. This may sound a bit confusing, but it is a simple thing that
Python will allow you to do. All that you need to do to make this happen is to
take the data that you have and change it over to a sound or image file, rather
than having it as a text file.
With Python, you can change any of the code that you want into a binary file.
It doesn’t matter what kind of file it was in the past. But you do need to make
sure that you work on the data in the right way to ensure that it is easier to
expose in the way that you want. The syntax that is going to be needed to
ensure that this will work well for you will be below:
# write binary data to a file
# writing the file hello. that write binary mode
F = open(‘hello. dat’, ‘wb’)
# writing as byte strings
f.write(“I am writing data in binary file!/n”)
f.write(“Let’s write another list/n”)
f.close()
If you take the time to use this code in your files, it is going to help you to
make the binary file that you would like. Some programmers find that they
like using this method because it helps them to get things in order and will
make it easier to pull the information up when you need it.
Opening your file up
So far, we have worked with writing a new file and getting it saved, and
working with a binary file as well. In these examples, we got some of the
basics of working with files down so that you can make them work for you
and you can pull them up any time that you would like.
Now that this part is done, it is time to learn how to open up the file and use
it, and even make changes to it, any time that you would like. Once you open
that file up, it is going to be so much easier to use it again and again as much
as you would like. When you are ready to see the steps that are needed to
open up a file and use it, you will need the following syntax.
# read binary data to a file
#writing the file hello. that write append binary mode
with open(“hello. dat”, ‘rb’) as f:
data = f.read()
text = data. decode(‘utf-8’)
print(text)
The output that you would get form putting this into the system would be like
the following:
Hello, world!
This is a demo using with
This file contains three lines
Hello world
This is a demo using with
This file contains three lines.
Seeking out a file you need
And finally, we need to take a look at how you can seek out some of the files
that you need on this kind of coding language. We already looked at how to
make the files, how to store them in different manners, how to open them and
rewrite on them, and then how to seek the file. But there are times where you
can move one of the files that you have over to a new location.
For example, if you are working on a file and as you do that, you find that
things are not showing up the way that you would like it to, then it is time to
fix this up. Maybe you didn’t spell the time of the identifier the right way, or
the directory is not where you want it to be, then the seek option may be the
best way to actually find this lost file and then make the changes, so it is
easier to find.
With this method, you are going to be able to change up where you place the
file, to ensure that it is going to be in the right spot all of the time or even to
make it a bit easier for you to find it when you need. You just need to use a
syntax like what is above to help you make these changes.
Working through all of the different methods that we have talked about are
going to help you to do a lot of different things inside of your code. Whether
you would like to make a new file, you want to change up the code, move the
file around, and more; you will be able to do it all using the codes that we
have gone through.
Chapter 11: Object Oriented Programming
Python classes make Python an object-oriented language. It is one of the most
effective approaches to writing software. You write classes to depict real-life
objects in programs. A class allows you to define the general behavior of a
real-life object. The class is equipped with the attributes of that object. You
can add more traits along the way. Any real-life object can be modeled on
classes. There is a feature known as instantiation in which you have to work
with instances. You will write certain classes that tend to extend the
functionality of existing classes.
Object-orienting programming allows you to create different objects. You
will able to see the world as a programmer does. You can be a creator of
things that exist in your imagination. You will think logically and write
programs that allow you to complete your tasks effectively and efficiently.
Classes make life easier for you as you move on to complex tasks in your
programming life.
But many of the newer programming languages have been changed to
become object oriented. These are easier to deal with and can be used in a
variety of different ways. Python is one of these object-oriented programming
languages, and you will be able to look at the objects and determine what
they are attached to. So, if you have a ball inside of the program or the code,
it should match up to the ball that you would find in real life. This helps to
keep things in order and even a beginner will be able to recognize how the
objects work inside of the code.
With that being said, you will also need to look for some of the attributes that
are in your code. The attributes are what is going to determine the object. An
excellent way to think about this is to pick out an object, such as a box. The
attributes would be the things that you would use to describe the object. So,
in this case, this is going to be brown, big, sturdy, square, and so on. These
should all make sense to others who would look at the box and want to
describe it. For example, you would not want to add in bouncing or flying to
the box, because these are not attributes that are usually given to the box.
These classes are also going to help you to organize some of the objects that
you are making. If there are a few objects that you are using, you will be able
to put them all inside the same class so that you are able to find them later on.
You are able to make the class be composed of anything that you would like,
but it is often better to make the items inside of the class be similar, so that
they make more sense and it keeps the code easy to work with. You may
have to think this through a little before you get started, but you should be
able to organize the objects that you are using into the right classes to help
the interpreter do the work the way that you would like.
Creating a Python Class
Python classes can be used to model anything such as a bird, an animal, or a
human being as well. In the following example, I will be writing a superman
class. I will attribute to it certain behaviors that you might have seen in a
superman cartoon or movie. You can study the code, understand, and then
create your own object on its basis. Before I create a superman class, I will
create an eagle class to make things easier for you. Let’s jump on to Python
editor. Each instance that is created from an Eagle class will have a name and
its age. After that, I will attribute certain behaviors to the Eagle class, such as
flying and attacking the prey.
class Eagle():
"""This is a simple try to model an Eagle."""
def __init__(self, ename, eage):
"""Time to kick name and age attributes."""
self.ename = ename
self.eage = eage
def fly(self):
"""This will simulate the eagle flying to a command."""
print(self.ename.title() + " is now flying high in the air.")
def attack(self):
"""This will simulate it to attack a prey in response to a command."""
print(self.ename.title() + " is attacking a rabbit!")
my_eagle = Eagle('Gamon', 5)
print("My eagle's name is " + my_eagle.ename.title() + ".")
print("The eagle is " + str(my_eagle.eage) + " years old.")
============= RESTART: C:/Users/saifia computers/Desktop/Python.py
=============
My eagle's name is Gamon.
The eagle is 5 years old.
>>>
This is an Eagle class. The last two lines of the code are the instance that I
have created. This is a kind instruction for the class on which it will act. You
can add as many instances in the Python class as you want to.
class Eagle():
"""This is a simple try to model an Eagle."""
def __init__(self, ename, eage):
"""Time to kick name and age attributes."""
self.ename = ename
self.eage = eage
def fly(self):
"""This will simulate the eagle flying to a command."""
print(self.ename.title() + " is now flying high in the air.")
def attack(self):
"""This will simulate it to attack a prey in response to a command."""
print(self.ename.title() + " is attacking a rabbit!")
my_eagle = Eagle('Gamon', 5)
print("My eagle's name is " + my_eagle.ename.title() + ".")
print("The eagle is " + str(my_eagle.eage) + " years old.")
my_eagle1 = Eagle('Timmy', 4)
print("My eagle's name is " + my_eagle1.ename.title() + ".")
print("The eagle is " + str(my_eagle1.eage) + " years old.")
my_eagle2 = Eagle('Flyer', 5)
print("My eagle's name is " + my_eagle2.ename.title() + ".")
print("The eagle is " + str(my_eagle2.eage) + " years old.")
============= RESTART: C:/Users/saifia computers/Desktop/Python.py
=============
My eagle's name is Gamon.
The eagle is 5 years old.
My eagle's name is Timmy.
The eagle is 4 years old.
My eagle's name is Flyer.
The eagle is 5 years old.
>>>
I have added three instances this time. That’s how you can add as many
instances to a Python class as you want to. I have told Python to create three
eagles who have different names and different age groups. When Python
reads this line, it calls on to the __init__ () method to create an object. The
__init__() method is known as a particular method in Python classes that
Python needs to run any new instance that you create for a class. There are
two leading and two trailing underscores in the script of the method. I have
allocated three attributes to the __init__() method. I will add one or two more
in the following example.
In the instance that I have created, I just passed the name and age of the bird
that was then applied by the __init__ method. I have also added two more
methods; one to make the eagle fly and the other to attack prey. You can add
as many methods as you like. In the following example, I will make the
program a bit more complex. Let’s see how it is done.
class Eagle():
"""This is a simple try to model an Eagle."""
def __init__(self, ename, eage, ecolor):
"""Time to kick name and age attributes."""
self.ename = ename
self.eage = eage
self.ecolor = ecolor
def fly(self):
"""This will simulate the eagle flying to a command."""
print(self.ename.title() + " is now flying high in the air.")
def attack(self):
"""This will simulate it to attack a prey in response to a command."""
print(self.ename.title() + " is attacking a rabbit!")
def rest(self):
"""This will simulate it to rest in response to a command."""
print(self.ename.title() + " is resting in the nest!")
my_eagle = Eagle('Gamon', 5, 'black')
print("My eagle's name is " + my_eagle.ename.title() + ".")
print("The eagle is " + str(my_eagle.eage) + " years old.")
my_eagle1 = Eagle('Timmy', 4, 'blue')
print("My eagle's name is " + my_eagle1.ename.title() + ".")
print("The eagle is " + str(my_eagle1.eage) + " years old.")
my_eagle2 = Eagle('Flyer', 5, 'grey')
print("My eagle's name is " + my_eagle2.ename.title() + ".")
print("The eagle is " + str(my_eagle2.eage) + " years old.")
============= RESTART: C:/Users/saifia computers/Desktop/Python.py
=============
My eagle's name is Gamon.
The eagle is 5 years old.
My eagle's name is Timmy.
The eagle is 4 years old.
My eagle's name is Flyer.
The eagle is 5 years old.
>>>
I have added more arguments to the function to make the class more
interactive. Now it is time to call all the functions to make the eagle do what I
made it do. I will make the eagle fly, attack, eat, and rest in the nest. It is
really amazing to see it do things that you want it to do.
class Eagle():
"""This is a simple try to model an Eagle."""
def __init__(self, ename, eage, ecolor):
"""Time to kick name and age attributes."""
self.ename = ename
self.eage = eage
self.ecolor = ecolor
def fly(self):
"""This will simulate the eagle flying to a command."""
print(self.ename.title() + " is now flying high in the air.")
def attack(self):
"""This will simulate it to attack a prey in response to a command."""
print(self.ename.title() + " is attacking a rabbit!")
def eat(self):
"""This will simulate it to eat in response to a command."""
print(self.ename.title() + " is eating the rabbit!")
def rest(self):
"""This will simulate it to rest in response to a command."""
print(self.ename.title() + " is resting in the nest!")
my_eagle = Eagle('Gamon', 5, 'black')
print("My eagle's name is " + my_eagle.ename.title() + ".")
print("The eagle is " + str(my_eagle.eage) + " years old.")
my_eagle.fly()
my_eagle.attack()
my_eagle.eat()
my_eagle.rest()
my_eagle1 = Eagle('Timmy', 4, 'blue')
print("My eagle's name is " + my_eagle1.ename.title() + ".")
print("The eagle is " + str(my_eagle1.eage) + " years old.")
my_eagle1.fly()
my_eagle1.attack()
my_eagle1.eat()
my_eagle1.rest()
my_eagle2 = Eagle('Flyer', 5, 'grey')
print("My eagle's name is " + my_eagle2.ename.title() + ".")
print("The eagle is " + str(my_eagle2.eage) + " years old.")
my_eagle2.fly()
my_eagle2.attack()
my_eagle2.eat()
my_eagle2.rest()
============= RESTART: C:/Users/saifia computers/Desktop/Python.py
=============
My eagle's name is Gamon.
The eagle is 5 years old.
Gamon is now flying high in the air.
Gamon is attacking a rabbit!
Gamon is eating the rabbit!
Gamon is resting in the nest!
My eagle's name is Timmy.
The eagle is 4 years old.
Timmy is now flying high in the air.
Timmy is attacking a rabbit!
Timmy is eating the rabbit!
Timmy is resting in the nest!
My eagle's name is Flyer.
The eagle is 5 years old.
Flyer is now flying high in the air.
Flyer is attacking a rabbit!
Flyer is eating the rabbit!
Flyer is resting in the nest!
>>>
When you want to call a method, you just need to give the name of the
instance that is, in my case, my_eagle, my_eagle1, and my_eagle2. You can
give any names to the attributes and methods, but if they are descriptive, it
will help you read through the code quickly and identify what is missing if
you are receiving error messages.
Chapter 12: Math and binary
Whether you’re using a simple command prompt, the Jupyter development
environment (check it out, it’s excellent!), or your favorite Python file editor,
you can import the math module by typing “import math”. This loads the
module and makes a number of mathematical functions available to you. On
a related note, other modules can be imported the same way, so if you’re
interested in how you can extend Python in the future, search for the list of
Python modules. It is quite extensive and diversified, and many of them are
used in fields like data science and machine learning.
One of the functions you’ll have access to is the square root function we
mentioned earlier. This isn’t part of basic Python, but after importing the
module, you can now try the following example:
import math
print (sqrt (36))
Oops! You get an error. But why? We imported the math module, didn’t we?
Yes, we did, but the problem is we still wrote the function the same way we
would declare normal, built-in functions. When using module functions, we
need also to include the name of the module, followed by a dot and then add
the function. Here’s how:
import math
x = 36
print (math. sqrt (36))
6.0
Now we have the result of the function, which is 6.0.
The math module we imported adds a great deal of functions, including
trigonometric, logarithmic, and hyperbolic functions, as well as constants
such pi. We’re not going to explore all of them because learning mathematics
is beyond the scope, mainly because only specific fields require advanced
notions beyond the standard operations you learned. But if you’re interested
nonetheless and you have some math knowledge, you can play around with
the following functions:
math. cos (x): This will return the cosine of x radians.
math. degrees(x): This function translates the angle of x from radians to
degrees.
math.e: The value of e is a constant equal to 2.7182…and it doesn’t require
parentheses. The same goes for pi, which is another constant. These are
exceptions to the rule.
math. log (x, y): Return the natural logarithm of x to base y.
math. factorial (x): This will return the factorial value of x.
There are a lot more functions included in the math module. If you plan to
pursue a path in data science or machine learning, you should look them up
and brush up on your skills in mathematics.
Binary and Text

Files can be classified into two distinct categories:


Binary Files: These files are used to store computer data in the form of bytes.
This is the computer’s native language, so whatever you see in these files is
unreadable to your eyes. Well, actually, you can learn binary and find out
what every combination of 0 and 1 means, but realistically you don’t want to
go through that. On a side note, if you open this kind of file using a text
editor, you’ll see a bunch of unreadable gibberish. For instance, you can open
an image file inside a text editor and you’ll see text, just not in characters
you’re familiar with. The text won’t mean anything to you, but you can read
it. Just don’t save and overwrite that file in text or you can cause some issues.
Binary files include the following examples: Executable files (.exe, .bin),
images (jpg, gif), pdf documents, compressed zip files, mp3 audio files,
videos, and fonts.
Text Files: These files are readable because they contain characters. So when
you run them inside an editor, you’ll see the text characters you’re used to.
However, this doesn’t mean you’ll understand what you’re reading because
they might not be set in a particular language.
Text files include the following examples: Simple text files like .txt and .csv,
source code files like your Python files, and data (json or xml).
The file types we mention are the most common ones you’re undoubtedly
familiar with. There are other files that are split into these two categories.
Before we get started with practical examples, take note that we’re going to
use Visual Studio Code as our coding editor instead of the usual Jupyter
notebook, Vim or the online Python console. You may have heard of Visual
Studio being used generally with other languages like C#, but it also offers
Python support. You don’t have to use this editor, though. Any will do just
fine. The reason why we’re going to play around with it is because it has a
handy Explorer bar to show us the folder/directory we’re in.
Chapter 13: Exercises
In your first program you had a single statement that was printed with the
print function. Keep in mind that you can also print any number of
statements, even in the same line, even if they are represented by several
variables. This is done with one of the most successful operations you will
perform on strings called concatenation. This concept is simple. All it
involves is linking multiple strings together. Here’s a simple example:
charRace = “human”
charGender = “male”
print (charRace, charGender)
The output will be “human male”.
As you can see, we have two variables and each one of them holds a string.
We can print both of them by separating the variables with commas when
writing the print statement. Keep in mind that there are multiple ways you
can do this. For instance, if you don’t want to use variables but you need to
concatenate the strings, you can get rid of the commas inside the print
statement. You will notice a little problem, though. Here’s the example:
print (“school” “teacher”)
The result is “schoolteacher”. What happened? We didn’t leave any
whitespace. Take note that whitespace can be part of a string just as numbers
and punctuation marks. If you don’t leave a space, words will be glued
together. The solution is to simply add one blank space before or after one of
the strings, inside the quotes.
Subsequent, let’s see what happens if you try to combine the two methods
and concatenate a variable together with a simple string.
print (charRace “mage”)
This is what you will see:
File "<stdin>", line 1
print (characterGender “warrior”)
^ SyntaxError: invalid syntax
Congratulations, you got your first syntax error. What’s the problem here?
We tried to perform the concatenation without using any kind of separator
between the two different items.
Let’s take a look at one more method frequently used to concatenate a set of
strings. Type the following:
x = “orc”
y = “ mage”
x+y
As you can see you can apply a mathematical operator when working with
string variables. In this case, we add x to y and achieve string concatenation.
This is a simple method and works just fine, however, while you should be
aware of it, you shouldn’t be using it. Mathematical operations require
processing power. Therefore, you are telling your Python program to use
some of your computer juice on an operation that could be written in such a
way as not to consume any resources. Whenever you work on a project, at
least a much more complex one, code optimization becomes one of your
priorities and that involves managing the system’s resource requirement
properly. Therefore, if you have to concatenate a large number of string
variables, use the other methods that don’t involve any math.
We’re going to carry on with If and Then in a bit but before we do, there’s
one more thing to consider: comparing variables.
Sometimes it will be useful to look at one variable and then compare that to
another variable. For instance, we might want to compare a string to a stored
password if we’re asking someone to log in. Alternatively, we might be
trying to find out if someone is older or younger than a certain age.
To do this, we have a few symbols and conventions. To ask if something
‘equals’ something else, we will use the symbol ‘==’ (using ‘==’ compares
two variables, whereas one ‘=’ forces them to be the same). This is what will
allow us to test certain conditions for our IF, THEN statements. This way we
can say ‘IF’ password is correct, ‘THEN’ proceed.
For example:
Password = "guest"
Attempt = "guest"
if Attempt == Password:
print("Password Correct")
This essentially tests the imaginary password attempt against the true
password and only says ‘correct’ when the two strings are the same. Notice
that we aren’t actually using the word ‘next’ at any point. In some
programming languages (such as BASIC) you actually do write ‘next’ but in
most it is implicit. Anything that comes after the colon is ensuing, which is
just the same way that loops work! Python is nice and consistent and it’s
actually a very attractive and simple language to look at when you code with
it well…
(That’s right – programming languages can be attractive! In fact, there is
even such thing as ‘code poems’!)
We can also use an input to make this a bit more interactive!
Doing this is very easy:
Password = "guest"
Attempt = input("Please enter password: ")if Attempt == Password:
print("Password Correct")
Try entering the right password and you should be presented with the correct
message – congrats!
There’s just one problem at the moment, which is that our user will still be
able to get into the program if they get the program wrong! And there is
nothing to tell them that they answered incorrectly…
Fortunately, we can fix this with our following statement: ‘else’.
As you might already have guessed, ‘else’ simply tells us what to do if the
answer is not correct.
This means we can say:
Password = "guest"
Attempt = input("Please enter password: ")if Attempt == Password:
print("Password Correct")
else:
print("Password Incorrect!")
Note that the ‘else’ statement moves back to be in-line with the initial ‘if’
statement. Try entering wrong passwords on purpose now and the new
program will tell you you’ve made a mistake!
Okay, so far so good! But now we have another problem: even though our
user is entering the password wrong and being told as much, they are still
getting to see whatever code comes subsequent:
Password = "guest"
Attempt = input("Please enter password: ")if Attempt == Password:
print("Password Correct")
else:
print("Password Incorrect!")
print(“Secret information begins here…”)
Of course this somewhat negates the very purpose of having a password in
the first place!
So now we can use something else we learned earlier – the loop! And better
yet, we’re going to use while True, break and continue. Told you they’d
come in handy!
Password = "guest"
while True:
Attempt = input("Please enter password: ")
if Attempt == Password:
print("Password Correct")
break
else:
print("Password Incorrect!")
continue
print("Secret information begins here...")
Okay, this is starting to get a little more complex and use multiple concepts at
once, so let’s go through it!
Basically, we are now starting a loop that will continue until interrupted.
Each time that loop repeats itself, it starts by asking for input and waits for
the user to try the password. Once it has that information, it tests the attempt
to see if it is correct or not. If it is, it breaks the loop and the program
continues.
If it’s not? Then the loop refreshes and the user has another attempt to enter
their password!
We’ve actually gone on something of a tangent here but you may recall that
the title of this was ‘Comparing Variables’. What if we don’t want to test
whether two variables are the same? What if we want to find out if one
variable is bigger than another? We can ask if something is ‘bigger’ using the
symbol ‘>’ and ask whether it is smaller using the ‘<’ symbol. This is easy to
remember – just look at the small end and the big end of the character!
Adding an equals sign will make this test inclusive. In other words ‘>=’
means ‘equal or bigger than’.
Likewise, we may also test if two strings are different. We do this like so:
‘!=’ which basically means ‘not equal to’.
Using that last example, we can turn our password test on its head and
achieve the exact same end result:
Password = "guest"
while True:
Attempt = input("Please enter password: ")
if Attempt != Password:
print("Password Incorrect!")
continue
else:
print("Password Correct")
break
print("Secret information begins here...")
Of course when you get programming you’ll find much more useful ways to
use this symbol!
Let’s Make Our First Game!
We’ve talked an awful lot of theory at this point so perhaps it’s time for us to
make our first game! It’s not going to be that much fun, seeing as you’ll
know the answer – but you can get your friends to play it to impress them
with your coding know-how (unfortunately, it’s still not all that fun even
then!).
The game is simply going to get the player to guess the number it is thinking
of and will then give clues to help them get there if they get it wrong.
CorrectNumber = 16
while True:
GuessedNumber = int(input("Guess the number I'm thinking of!"))
if GuessedNumber == CorrectNumber:
print("Correct!")
break
elif GuessedNumber < CorrectNumber:
print("Too low!")
continue
elif GuessedNumber > CorrectNumber:
print("Too high!")
continue
print("You WIN!!!")
Conclusion
Now that we have come to the end, I hope you have gathered a basic
understanding of what machine learning is and how you can build a machine
learning model in Python. One of the best ways to begin building a machine
learning model is to practice the code, and also try to write similar code to
solve other problems. It is important to remember that the more you practice,
the better you will get. The best way to go about this is to begin working on
simple problem statements and solve them using the different algorithms.
You can also try to solve these problems by identifying newer ways to solve
the problem. Once you get a hang of the basic problems, you can try using
some advanced methods to solve those problems.
Thanks for reading to the end!
Python Machine Learning may be the answer that you are looking for when it
comes to all of these needs and more. It is a simple process that can teach
your machine how to learn on its own, similar to what the human mind can
do, but much faster and more efficient. It has been a game-changer in many
industries, and this guide tried to show you the exact steps that you can take
to make this happen.
There is just so much that a programmer can do when it comes to using
Machine Learning in their coding, and when you add it together with the
Python coding language, you can take it even further, even as a beginner.
The succeeding step is to start putting some of the knowledge that in this
guide to good use. There are a lot of great things that you can do when it
comes to Machine Learning, and when we can combine it with the Python
language, there is nothing that we can’t do when it comes to training our
machine or our computer.
This guide took some time to explore a lot of the different things that you can
do when it comes to Python Machine Learning. We looked at what Machine
Learning is all about, how to work with it, and even a crash course on using
the Python language for the first time. Once that was done, we moved right
into combining the two of these to work with a variety of Python libraries to
get the work done.
You should always work towards exploring different functions and features
in Python, and also try to learn more about the different libraries like SciPy,
NumPy, PyRobotics, and Graphical User Interface packages that you will be
using to build different models.
Python is a high-level language which is both interpreter based and object-
oriented. This makes it easy for anybody to understand how the language
works. You can also extend the programs that you build in Python onto other
platforms. Most of the inbuilt libraries in Python offer a variety of functions
that make it easier to work with large data sets.
You will now have gathered that machine learning is a complex concept that
can easily be understood. It is not a black box that has undecipherable terms,
incomprehensible graphs, or difficult concepts. Machine learning is easy to
understand, and I hope it has helped you understand the basics of machine
learning. You can now begin working on programming and building models
in Python. Ensure that you diligently practice since that is the only way you
can improve your skills as a programmer.
If you have ever wanted to learn how to work with the Python coding
language, or you want to see what Machine Learning can do for you, then
this guide is the ultimate tool that you need! Take a chance to read through it
and see just how powerful Python Machine Learning can be for you.

You might also like