Kevin Cooper - Computer Programming For Beginners - 3 Books in 1 - Step by Step Guide To Learn Programming, Python For Beginners, Python Machine Learning
Kevin Cooper - Computer Programming For Beginners - 3 Books in 1 - Step by Step Guide To Learn Programming, Python For Beginners, Python Machine Learning
Beginners
- 3 Books in 1 -
Step by Step Beginners’ Guide to
Learn Programming, Python For
Beginners, Python Machine Learning
By
Kevin Cooper
Books In the “PROGRAMMING LANGUAGE” Series by Kevin Cooper
TITLE WHAT'S THE BOOK ABOUT SINGLE BOOK OR BUNDLE
PYTHON MACHINE The Ultimate and Complete Guide for SINGLE BOOK
Beginners on Data Science and
LEARNING and
Machine Learning with Python
AUDIOBOOK
(Learning Technology, Principles, and
Applications)
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.
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.
Introduction
Chapter 1: Introduction to Python
What is Python?
Python and its History
Python and Its Features
First Python Program
Building Development Environment
Use of Interactive Command Line
Python Development Tools
Python Under Different Platforms
Chapter 2: Variables and Constants in Python
Why Variables are needed?
Variable Naming and Assignment
Static Type and Dynamic Type
Python's Numeric Data Types
Decimal Module
Constant
Formatting Input and Output Function
Hands-on Practice Exercise
Chapter 3: Operators in Python
Why are Operators Necessary?
What are Operands and Operators?
Operator Precedence
Hands-on Practice Exercise
Chapter 4: Conditional and Loops in Python
What is a sequence in Python?
Selection Process Control
If...Else Conditional Statement
Multiple Choices
The Loop Repeat Structure
Practical Exercises
Chapter 5: Modules and Functions in Python
Python Program Structure
Module Creation
Module Import
Properties of Modules
Custom Packages
Function
Chapter 6: Object-oriented Programming in Python
What Is Object-Oriented Programming?
Overview of Object-Oriented Programming
Categories and Objects
Chapter 7: Files in Python
What are Files in Python?
Conclusion
BOOK 3: Python Machine Learning
Introduction
Chapter 1: What is Data Science and Deep Learning?
Why Data Science Is Important
What is Data Science?
Predictive casual analytics:
Prescription analytics:
Making predictions through machine learning:
Machine learning for the discovery of the pattern:
Data Science vs. Business Intelligence (BI)
Data Science Lifecycle
Phase 1 – Discovery:
Phase 2 – Preparation of data:
Phase 3 – model planning:
Phase 4 – Building the model:
Phase 5 – Operationalize:
Phase 6 – Communicate results:
Secret Sauces of Data Scientists
An In-depth Look into Deep Learning
Chapter 2: Data Science and Applications
Banking and Finance
Fraud detection
Customer data management
Investment banks risk modeling
Personalized marketing
Health and Medicine
Analysis of medical image
Genomics and genetics
Drugs creation
Virtual assistance for customer and patients support
Industry knowledge
Oil and Gas
Immediate drag calculation and torque using neural networks
Predicting well production profile through feature extraction models
Downstream optimization
The Internet
Targeted advertising
Website recommendations
Advanced image recognition
Speech recognition
Travel and Tourism
Customer segmentation and personalized marketing
Analysis of customer sentiment
Recommendation engine
Travel support bots
Route optimization
Chapter 3: Probability – Fundamental – Statistics – Data Types
Real-Life Probability Examples
Organize around the weather
Strategies in sports
Insurance option
Recreational and games activities
Statistics
Statistics in data analysis
Data Types
Categorical data
Nominal data
Ordinal data
Numerical Data
The Importance of Data Types
Statistical Methods
Nominal data
Ordinal data
Continuous data
Descriptive Statistics
Normal Distribution
Central tendency
Chapter 4: Linear Algebra
The Importance of Linear Algebra
Example 1:
Example 2:
Example 3:
Example 4:
Linear Algebra Problems Representation
Visualize the Problem
Complicating the Problem
Planes
Matrix
Matrix’s related words
Chapter 5: Understanding the Fundamentals of Machine Learning
Prerequisites to start with machine learning
The semantic tree
Six Jars of Machine Learning
Learning
Loss
Task
Data
Evaluation
Model
Supervised learning
Machine Learning Roadmap
Linear Regression
Logistic Regression
Naive Bayes Classifier
K – Nearest Neighbors (KNN)
K – Means
Support Vector Machine (SVM)
Decision Trees
Random Forest
Gradient Boosting
Chapter 6: Types of Machine Learning
Types of Machine Learning Algorithms
Algorithms of supervised machine learning
Use cares of supervised learning algorithms
Algorithms of unsupervised machine learning
Unsupervised learning machine used cases
Algorithms of semi-supervised machine learning
Use cases of semi-supervised machine learning
Algorithms of Reinforcement Machine Learning
Reinforcement machine learning algorithms use cases
Pattern Recognition and why it Matters
What is pattern recognition?
Pattern recognition models
How pattern recognition works
Pattern recognition use cases
Chapter 7: What is Python? Setting Up the Environment in Python
The Use of Python
Benefits of learning Python
Python Environment Setup
Text File vs. Python Shell
The Best Place to Start
How to get Python
The version of Python to use
Features of Python
What is Django?
The Difference between Python and Other Languages
The use of the languages
Chapter 8: Guide to Machine Learning With Python
The basic need for machine learning
When and why making machines learn?
Machine Learning with Python – Ecosystem
Python’s strengths and weaknesses
Why Python for Data Science?
An extensive set of packages
Easy prototyping
Collaboration feature
Many domains with one language
Machine Learning Techniques with Python
Machine learning regression
Classification of machine learning
Clustering
Anomaly detection
Data Loading for Machine Learning Projects
Consideration while loading CSV data
Methods of loading CSV data file
Load CSV with Python standard library
Load CSV with MumPy
Load CSV with Pandas
Applications of Machine Learning with Python
Virtual personal assistants
Social media services
Online customer support
Online fraud detection
Product recommendations
Refining search results
Fighting web spam
Automatic translation
Video surveillance
Chapter 9: K – Nearest Neighbor Algorithms – K – Means Clustering
K – Nearest Neighbors
The KNN Algorithm
Selecting the right value for K
KNN in practice
How to Implement K – Nearest Neighbors in Python
Handle data
Similarity
Neighbors
Response
Accuracy
Main
K – Means Clustering
Clustering
K – Means Algorithm
Data assignment step:
Centroid update step:
Choosing K
Business Uses
Behavioral segmentation:
Inventory categorization:
Measurements of sorting sensor:
Anomalies and bots detection:
Chapter 10: Neural Networks – Linear Classifiers
Neural Network Elements
Deep Neural Networks Key Concepts
Feedforward Networks
Multiple Linear Regression
Different Types of Classifiers
Conclusion
Step by Step Beginners’ Guide to
Learn Programming
The Complete Introduction Guide for
Learning the Basics of C, C#, C++,
SQL, JAVA, JAVASCRIPT, PHP, and
PYTHON.
A Pratical Programming Language
Course
By
Kevin Cooper
Chapter One: Introduction to
Programming
Thank you for buying this book because it is the best investment you will
make in improving your skill as a programmer. The book contains
information on the basics of programming in various programming languages
including PHP, JavaScript, Java, Python, SQL, C+, C#, and C.
I am Kevin Cooper and if you are a beginner, do not worry because I started
the same way as you are about to do. I will be your driver and guide for this
wonderful journey of the beginners’ guide to learning programming.
The book is geared towards you understanding the aforementioned
programming languages in its simplicity. I will teach you in a way that you
will not forget. The book contains exercises, which is important for you to
practice if you want to be a productive and successful programmer.
Today, we have seen hundreds of programming languages created for
different purposes. However, we have also seen some of these programming
languages gaining more popularity over others.
No matter what your quest is, welcome to the world of programming where
everything is possible. Programming is simply the act or process of writing
programs to instruct the computer what actions to perform or not. These
programs use various series of instructions in a particular language (all
language have different instruction). Nevertheless, in this book, you learn the
fundamentals of seven programming languages. These languages include C,
C++, C#, SQL, Java, PHP, and Python.
Programming isn’t complicated as many try to portray it. If that has been
your perception, this step by step beginners’ guide to learn programming will
change that perception. It is surely going to be a fun ride as long as you stick
to what is contained in this book. I am confident this book contains
everything you need as a beginner, who is looking forward to going into
advanced coding. Let’s crack the nuts together.
Introduction
The C programming language is one of the most commonly used languages
with various versions developed over the years. The C language is the
fundamental language to understand before considering learning the C# and
C++ language. My goal in this chapter is to enable you to have the
fundamental knowledge concerning the basics of C programming language
including the various data types.
Before starting, it is important to familiarize yourself with the language. The
C programming language is also referred to as a general-purpose because
programmers can use it for varieties of application. Its popularity is linked to
its efficiency despite how old it has been in existence. Most C programs are
portable, which means that a code written in a particular system can work in
another operating system.
Let’s assume you want the following statement to show on the screen.
“Hello, Welcome to C Programming Language for Beginners” on the screen,
it will be as follow.
#include <stdio.h>
/* the int main () is the part where the execution of the program
begins*/
Int main ()
{
/* Performing the First Programming Sample in C language*/
Printf(“Hello, Welcome to C Programming Language for
Beginners”);
Getch();
Return 0;
}
Output
To ensure you write a program in C language and get the output, there are
important steps to follow. There is no exception to these steps as far as it is a
C program. It doesn’t matter if it is a small or large program. These involve
the creation, compilation, execution (running), and outputting of the program.
For you to do this there are certain prerequisites
You must have a C compiler installed on your system. With this,
you can execute programs.
It is not compulsory to install one on your system as you can
instead use an online compiler to compile and execute your
programs. Just search for online compilers for C and you will get
more details.
Data Types
A data type is a very simple but important concept to understand in any
programming language. It is a representation of a particular type of data,
which is processed through a computer program. A particular data type
determines a storage space along with the manner the bit pattern is
understood when processing the data.
In C language, data types are categorized into four different groups
Types Data Types
Enumeration data type Enum
Basic Data Int, float, char, double
Derived data type Pointer, array, union, structure
Void data type Void
Identifiers are names given to entities like functions, variables, structures, etc.
They are unique and created to an entity within the execution of the program.
For instance,
Literals
These are values whose value cannot be changed in the course of the
program. The term is used in place of constant, so when you see constant
they mean the same thing. Constants comprise of various data types including
integer, character, floating, and string.
An integer constant on no situation must have an exponential or fractional
part. We have three integer literals in C programming. These are:
Decimal (example: 54, -98, 11)
Octal (example: 042, 089, 044)
Hexadecimal (example: 0x9f, 0x345, 0x7a)
Floating-point literals are numerical literal with an exponent or fractional
part. For instance, -4.0, 0.0000345, -0.44E-9.
Characters are literally formed by enclosing them with a single quotation
mark. For instance: ‘t’, ‘h’, ‘8’, etc;
Finally, a string literal comprises of a sequence or collection of characters
encircled in double quotation marks. For instance, “love”, “C Programming”,
“Professional”
Arithmetic Operators
In C programming language, these operators perform mathematical operators
namely addition, subtraction, division, multiplication. These can be executed
on various numerical values.
Operator Meaning Example
+ Addition A + C = 50
* Multiplication A * C = 10
- Subtraction A – C = 20
/ Division A/C= 5
% Modulo division C/A =0
++ Increment by 1 C++
-- Decrement by 1 C--
Example 1
#include <stdio.h>
main()
{
int day1 = 31;
int = day2;
int day3 ;
final = day1 + day2;
printf("First Line - Value of day3 is %d\n", day3 );
day3 = day1 – day2;
printf("Second Line - Value of day3 is %d\n", day3 );
day3 = day1 * day2;
printf("Third Line - Value of day3 is %d\n", day3 );
day3 = day1 / day2;
printf("Fourth Line - Value of day3 is %d\n", day3);
day3 = day1 % day2;
printf("Fifth Line - Value of day3 is %d\n", day3 );
day3 = day1 ++;
printf("Sixth Line - Value of day3 is %d\n", day3 );
day3 = day2--;
printf("Seventh Line - Value of day3 is %d\n", day3);
}
If you compile this program and it executed successfully, your output will be
as follows: First Line - Value of day3 is 51
Second Line - Value of day3 is 11
Relational Operators
The role of these operators is to verify the relationship or association that
exists between two different operands. The table below shows the basic
relational operators in the C language. Assuming the value for loss and profit
are “25” and “35” respectively.
Operator Meaning Example
== This operator loss==profit is
evaluates whether the evaluated as not true
value is equivalent or
not to the second
value on the right. If
it is true, the condition
turns out to be true.
> The operator verifies From the value, loss
if the left operand >profit is false true
greater than that on
the right side
< The operator verifies loss < profit is true
if the left operand is
less than that of the
right side
!= The operator verifies loss !=profit returns
if the operand on the true
left side fulfill the
condition by not being
equivalent to the one
on right side
>= This verifies if the left loss>=profit returns
operand is either not true
greater or equivalent
to the right operand
<= This verifies if the loss<=profit is true
operand on the left is
either less or
equivalent to the right
operand
Program output:
First Line - day is not equal to week
Second Line - day is not less than week
Third Line - day is greater than week
Fourth Line - day is either less than or equal to week
Fifth Line - day is either greater than or equal to week
Bitwise Operators
These special operators are used in manipulating data at the bit level. It is
used to shift bits from the right position to the left. Nevertheless, they don’t
work with double float variables.
Bitwise Operator Meaning
| OR
^ Exclusive OR
& AND
<< Left Shift
>> Right Shift
Truth Table for bitwise operator
Y Z Y^Z Y|Z Y&Z
0 1 1 1 0
1 0 1 1 0
0 0 0 0 0
1 1 0 1 1
The table above to explain the bitwise operator will make no sense if you are
a beginner; the following explanation will clarify it for you. For instance, Y =
60 and Z = 13, the binary format of Y and Z will be 0011 1100 and 0000
1101 respectively
Y = 0011 1100
Z = 0000 1101
From the truth table,
Y | Z = 0011 1101
Y&Z = 0000 1100
Y ^ Z = 0011 0001
I know you may be thinking about how we came about the values below;
well it is very simple to understand. Using the Y & Z as an example, the
value for Y is 0011 1100 while that of Z is 0000 1101. From the truth table,
we go under the Y & Z section. When Y is 0 and Z is 1, what is the value
under Y & Z (What you are doing is matching the first binary number of Y
with that of Z? obviously, you get a 0. If you continue with that patter, you
will get 0000 1100 for Y & Z.
Assignment Operators
The table below will give a better view of what assignment operators work in
C programming.
Assignment Operators Meaning Example
= This allocates the V=B+D
value of the right In his situation, the
operand to left value of B + D will be
operand assigned to V
*= The left operand gets V* = B is equal to
multiplied V= V*B
by the right operand.
furthermore, the
product is then
allocated to the left
operand.
-= This deducts the value V -=B
of operand on the This is equivalent to
right from the left V=V-B
before assigning it to
the left.
+= This adds the value of V+= is equivalent to
the right operand from V=V+B
the left before
allocating the value to
the content on the left
/= In this, the value of V/= is equivalent to
the operand on the left V = V /D
is divided by the right
before assigned to the
left
Decision Making in C
It is hard to write a complete program without using decision in C language.
What do you think decision-making involves in the context of programming?
Well, it is a way of executing certain statements as long as they meet the laid
down conditions. However, you will learn the statement, format, and an
example to explain the decisions. The diagram below shows a typical
decision-making process in C.
If Statement
This mentions a particular condition and specifies a particular thing will
happen if the stated condition or statement becomes true. However, if the
condition doesn’t turn out true, then the thing suggests will not happen.
Format:
if (boolean_condition){
/* expression (s) that will perform the action if the Boolean condition
stated is true */
}
Diagrammatic representation
Once you finish and the program is executed, your output will look like this:
If … else Statement
This decision making statement uses an If, which is accompanied by an
optional statement that performs the action when the “IF” condition turns
false.
Format:
if(expression or condition){
/* this statement here will be executed as far as the condition is met */
}
Else{
/* expression (s) will be implement if the expression is not true */
}
Diagrammatic Representation
Output:
length is not less than 40;
value of length is: 200
Conclusion
The c programming language is not a hard language to learn because it is
fundamental for any beginner. If you have completed reading this chapter, I
can guarantee that you have the basic knowledge of C programming.
However, it is important to dive deeper if you want to perfect your skill with
this language.
Chapter Three: C# Programming
Introduction
Did you know that C# is an object-oriented language? Actually, Microsoft
developed the language as part of its inbuilt .NET initiative. This
programming guide on C# will take you through the basics of C# while
equipping you with every concept, you need to understand and relevant
programs to explain the language better.
Features of C# Language
While C# is narrowly similar to various high-level languages such as C and
C++ with strong resemblance with Java, however, it does still have a strong
programming feature that makes it popular among many programmers in the
world. The features include:
Integration with Windows
Indexers
Simple multithreading
Standard library
Boolean conditions
Easy to use generics
Properties and events
Assembly versioning
Automatic garbage collection
Data types
Nothing should be new to you at this point, because some of these terms have
been explained in previous chapters. However, it is important to throw more
light on them once a while. The C# language has its own basic data types,
which we will discuss in this section. You can use data types in C# to build
values that will be used in the course of the program or application. Let us
expound on these data types with example.
Integer
Integer data types work with numbers, which are normally whole numbers.
C# uses the reserves word “Int32” to declare a variable as an integer type. For
instance, if I declare the variable number1 as an integer. After this, I will
further allocate a numerical value to number1
using System;
namespace DemoProgram
{
class Program
//This part creates a new class, which we call Program
{
static void Main(string[] args)
{
Int32 number1=50;
Console.Write(number1);
Console.ReadKey();
}
}
}
Double
This data type is used when decimal numbers are involved. Examples include
10.58, 25.98, or 45.01. In C#, the keyword “Double” is used to denote a
double data type. In the example below, the variable “number1” is defined as
double and a value assigned to it.
using System;
namespace DemoProgram
{
class Program
// This part creates a new class, which we call Program
{
static void Main(string[] args)
{
// Declaration of the variable “number” to be of double data type
double number1=45.01;
Console.Write(num);
Console.ReadKey();
}
}
}
Boolean
The Boolean data type works with Boolean values, which can only be false or
true. The keyword “Boolean” is used to declare this kind of datatype. For
instance, the program below declares “OFF” as Boolean with the value
“False” assigned to it. Eventually, the console display “False” as the output.
using System;
namespace DemoProgram
{
class Program
// We create a new class call Program
{
static void Main(string[] args)
{
// Here is the declaration of the variables as Boolean
Boolean OFF=false;
Console.Write(status);
Console.ReadKey();
}
}
}
String
At times, when writing a program, you may choose to write a specific
message shown on the screen. To do this, the “string” data type allows text to
be displayed. It uses the keyword “String”
using System;
namespace DemoProgram
// The goal of this program is to display a string on the screen
{
class program
// We create a new class called Program
{
static void Main(string[] args)
{
String statement1="This is C# Programming for Beginners’.";
Console.Write(statement1);
Console.ReadKey();
}
}
}
Variables
In C#, it is a memory location that contains a data type that determines the
kind of value to store in the variable. Variables are declared in the format
below:
[modifiers] data type identifier;
The modifier in the format above represents an access modifier. On the other
hand, the identifier represents the variable name. The first example below
shows a variable declaration where the public is the modifier, number1 is an
identifier name, and int is the data type. However, the second example
indicates that the second variable type is a local variable.
Public int number1; // First example
Int number1; // second example
Variable Modifiers
A modifier allows a programmer to specify some features, which is applied to
the identifier. A local variable has a scope, which is defined within the block
in the program.
Modifier Meaning
Internal Accessible only by the current
program
Public Accessible as a field anywhere in
the program
Protected Accessible within the class it is
defined
Private Accessible within the type in
which it is defined
Constants
Constants are values whose values don’t change throughout the program time
frame. C# uses the keyword “const” and it always comes before the data type
and variable. If you decide to allocate value to a particular constant, it will
return compilation error. For instance,
const int number1 = 45;
number1 = 89;
// This will be a compilation error because the assignment towards the left
side has to be an indexer, variable or property.
Note that local variables can be declared as constants. These constants are
usually static, even if they don’t use any static keyword.
Operators in C#
You should be familiar with operators even if you are a beginner. These are
symbols used in programming to perform various operations on an operand.
Operands can be either constants or variables. For instance, in 3 * 6, * is an
operation used to perform multiplication operation whereas 3 and 6 are the
operands. You can use operators in C# to manipulate values and variables in
the course of a program. However, C# supports numerous operators
depending on the operation type they perform. Without much time, let us
begin with the operators in C#.
Arithmetic Operators
These operators are used for various numeric data types, which includes
arithmetic operations including addition (+), subtraction (-), multiplication
(*), and division (/). Furthermore, C# has another unique arithmetic operator
known as the %, which is the remainder after a division operation is
performed.
Importantly, unlike other languages, the operator + (addition) operate
differently when used with string and number types. For instance, the result
of the expression 7 + 4 is 11. However, when used with strings, the result of
the expression, “7 +4” is “74”. Therefore, with the number type, it acts as an
addition whereas with strings, it is a concatenation operator. A simple
program can be helpful to set things in order.
using System;
namespace Oper
{
class ArithmeticOper
{
// Always remember you have to create a new class by using the class
statement
public static void Main(string[] args)
{
double income = 12.20, expenses = 2.30, res;
int loss = 21, profit = 4, ; dem
// Addition operator (+)
res = income + expenses;
Console.WriteLine("{0} + {1} = {2}", income, expenses,
res);
res = income - expenses;
Console.WriteLine("{0} - {1} = {2}", income, expenses,
res);
When you properly compile this program without any error, you will get the
following output.
12.2 + 2.3 = 14.5
12.2 – 2.3 = 9.9
12.2 * 2.3 = 28.06
12.2 / 2.3 = 5.30434782609
21 % 4 = 1
Logical Operators
You can use these operators to perform logical operations and they include
AND, OR. These operators operate on Boolean expression and return the
same Boolean values. The result can only be true (T) or false (F) as illustrated
in the table below.
Operand Y Operand Z AND (&&) OR (||)
T T T T
F T F T
T F F T
F F F F
From the table, the OR operator evaluates to true (T) only in a situation
where one operand is true (T). However, for the AND operator, once one
operand is false (F), the operation is also False.
Sample program
using System;
namespace Operator
{
class Logical
// Here, we name the class we created as Operator
{
public static void Main(string[] args)
{
// Declaration and giving variables values
bool outcome;
int income = 20, expenses = 30;
// OR operator
outcome = (income == expenses) || (income> 5);
Console.WriteLine(outcome);
// AND operator
outcome = (income == expenses) && (incomeb > 5);
Console.WriteLine(outcome);
}
}
}
Relational Operators
These operators in C# return either a true or a false result. If you want to
compare variables or expression, the best option is the relational operator.
Additionally, they have a lower priority in comparison with arithmetic
operators. Besides this, you can use them in loop and decision-making. The
table below shows the basic relational operators in C#.
Relational Operators Name of Operator Example
== Equal to 6 == 7 return false
!= Not equal to 5 != 7 return true
> Greater than 7 > 5 returns true
< Less than 8 < 9 evaluates true
<= Less than or 9<= 7 evaluates true
(equivalent) equal to
>= Greater than or equal 5 >= 7 returns false
to
Sample Program
using System;
namespace Oper
{
class Relational
{
public static void Main(string[] args)
{
// Declaration of variables
int outcome;
int day1 = 21, day3 = 23;
outcome = (day1==day3);
Console.WriteLine("{0} == {1} returns {2}",day1, day3,
outcome);
outcome= (day1 > day3);
Console.WriteLine("{0} > {1} returns {2}",day1, day3,
outcome);
outcome = (day1< day3);
Console.WriteLine("{0} < {1} returns {2}",day1, day3,
outcome);
outcome = (day1 >= day3);
Console.WriteLine("{0} >= {1} returns {2}",day1, day3,
outcome);
outcome = (day1 <= day3);
Console.WriteLine("{0} <= {1} returns {2}",day1, day3,
outcome);
outcome = (day1 != day3);
Console.WriteLine("{0} != {1} returns {2}",day1, day3,
outcome);
}
}
}
Output:
20 == 30 returns False
20 > 30 returns False
20 < 30 returns True
20 >= 30 returns False
20 <= 30 returns True
20 != 30 returns True
Unary Operators
These operators unlike the ones we have discussed so far operate on one
operand instead of both. The unary operators in C# include
Operator Name Description
- Unary Minus Inverts the operand
sign
+ Unary Plus Leaves the operand to
sign the way it is
-- Decrement Decreases value by 1
++ Increment Increase value by 1
namespace UnaryOperator
{
class UnaryOpe
{
public static void Main(string[] args)
{
// Declaration of variables in the program
int num = 25, outcome;
bool flag = false;
outcome = +num;
Console.WriteLine("+num = " + outcome);
outcome = -num;
Console.WriteLine("-num = " + outcome);
outcome = ++num;
Console.WriteLine("++num = " + outcome);
outcome = --num;
Console.WriteLine("--num = " + outcome);
Console.WriteLine("!flag = " + (!flag));
}
}
}
+num = 25
-num = -25
++number = 26
--number = 25
!flag = True
Bitwise Operators
In our last operators in C# is the bitwise operator, which performs bit
manipulation similar to what I have explained in the preceding chapter. Since
you are familiar with the operation, I will simply highlight the operators and
a simple program to demonstrate how they work. For more, you can check
“Chapter Two” to refresh your memory.
namespace OperBit
{
// Creating a new class known as BitOpe
class BitOpe
{
If the program doesn’t contain any error, your output should be as follows:
~20 = -21
20 & 30 = 0
20 | 30 = 50
20 ^ 30 = 50
20 << 2 = 40
20 >> 2 = 2
Ternary Operator
This operator will be strange because it is the first time I am mentioning it in
this book. The ternary operator “?” operates on three operands and functions
like the “if… then… else” statement.
Format:
Variable = condition? Statement1: statement2;
The operation works this way. If the condition stated is true, then the
outcome of statment1 is allocated to the variable. However, if it turns out to
be false, the value is allocated to statement2. Consider the program below.
using System;
namespace OperTer
{
class Ternary
// The new class name for this program is Ternary
{
public static void Main(string[] args)
{
// Declaration of variables as integer and string
int num = 21;
string outcome;
outcome = (num % 2 == 0)? "Even Number" : "Odd
Number";
Console.WriteLine("{0} is {1}", num, outcome);
}
}
}
21 is Odd Number
namespace demoProgram {
class programArray
{
// Study the program carefully how the array is declared
Static void main (string[] args)
Int [] Table;
}
}
}
In the example above, you have an idea of the line – Int [] numbers;
So far, you should know that we are using an integer data type. The [] is the
placeholder, which specifies the array rank. It identifies the exact number of
elements contained in that array we want. Lastly, the array has a name, which
in this example is “Table”
Let’s go further with this example, consider the next line of codes.
using System;
namespace demoApplication {
class ArrayProgram
{
Static void main (string[] args)
Int [] Table;
Table = new Int [5];
Table [0] = 8;
Table [1] = 9;
Table [2] = 10;
Table [3] = 11;
Table [4] = 12;
Table [5] = 13
}
}
}
namespace DemoApplication
{
class ArrayProgram
{
static void Main(string[] args)
// Declaration of variables begins here
{
Int[] Table;
Table=new Int[3];
Table [0] = 8;
Table [1] =9;
Table [2] = 10;
Table [3] = 11;
Table [4] = 12;
Table [5] = 13;
Console.WriteLine(Table[0]);
Console.WriteLine(Table[1]);
Console.WriteLine(Table[2]);
Console.WriteLine(Table[3]);
Console.WriteLine(Table[4]);
Console.WriteLine(Table[5]);
Console.ReadKey();
}
}
}
using System;
namespace demoProgram {
class program
// Beginning of the program
{
Static void main (string[] args)
// Declaration of elements in the array
string [] stringArray = new string [20];
bool [] boolArray = new bool [2];
char [] charArray = new char [7];
double [] doubleArray = new double [4];
}
}
}
Categories of Array in C#
You can categorize arrays into four groups. These include single-dimensional
arrays, rectangular arrays or multidimensional arrays, jagged, and mixed
arrays. My focus will be on the first two arrays because jagged and mixed
arrays will be complicated for you to understand as a beginner.
Single-Dimensional
These set of arrays are the simplest and easiest to understand in C#. You can
use single-dimensional arrays to store items of an array with an already
predefined data type. The items in the array are stored continuously
beginning from 0. So far, all the arrays I have explained in this chapter are
single-dimensional arrays.
The code below declares and sets an array containing five items, with all
having an integer data type. First is to declare the array before instantiating
the array using the new operator.
int [] numberArray;
numberArray = new int [5];
C# uses a straightforward way of declaring arrays by putting the items in
curly braces. Note that if a program forgets to initialize the array, the items
are inevitably initialized to its definite original value for that array type. The
code below should explain it better.
1 int [] staticIntArray = new int [5] {2, 4, 6, 8, 10};
2 string [] strArray = new string [4] {“Johnson”, “Mikel,
“Frederick”, “Mahesh”};
3 string [] strArray = {“Johnson”, “Mikel, “Frederick”, “Mahesh”};
From the three different codes, you will observe that the first example
declares an array with 5 items. The second declares an array with string data
type having 4 string items. However, the second and third examples are the
same with the only difference being that we directly assigned the values to
the array without using the new operator.
Multi-Dimensional
This kind of arrays contains more than one dimension. Most beginners tend
to run away from this kind of arrays because they look complex. It has the
form of a matrix. This type of array can be of fixed or dynamic size.
However, to declare a multi-dimensional array, the format is as follows:
string [,] mutliDimStringArray
What if you are unsure the items the array will contain?. The code below
clarifies that by creating two-dimensional arrays without any limit to the
number of items.
Similar to the single-dimensional array where we omit the new operator, you
can also do the same in multi-dimensional arrays by directly assigning the
values.
namespace demoApplication {
class programArray
{
// Don’t forget we always have to create a new class
Static void main (string[] args)
int[, ] MyTable = {
{
4,
2
},
{
5,
2
},
{
1,
3
}
};
string[, ] names = {
{
"Queen",
"Ben"
},
{
"Paul",
"Irene"
}
};
}
}
}
The code above may look complicated but we can make it simpler by
initializing the array items one after the order. Look at the code below
int [, ] numb = new int [3, 2];
numb [0, 0] = 4;
numb [1, 0] = 2;
numb [2, 0] = 5;
numb [0, 1 ] = 2;
numb [1, 1] = 1;
numb [2, 1] = 3;
Brief History
In 1979, Bjarne Stroustrup developed C++ Programming language.
Originally, the language was known as “C with classes” before the name was
changed to C++ in 1983. The name is a demonstration that the language
comes from the C programming language. Today, the language has evolved
with C++14 as the standard C++. This version comes with added feature
including the fixing of some bugs. The introduction of the C++14 took place
on March 2014.
Is there anyone using C++?
The language is relevant in various sectors in the software industry. it may
surprise you to know that the OS of your favorite Apple laptop is written in
C++. Besides it, operating systems such as Windows 95, 98, Me, 2000, and
the once-popular Window XP were also written in this language.
Applications such as Internet Explorer, Microsoft Office, applications of
Adobe Systems (Illustrator, ImageReady, Flash, Photoshop, Acrobat, etc.) are
developed using C++. Furthermore, not forgetting the renowned Chromium
Web Browser, and Google Search engine, these are just a few to mention.
The panel on the left side represents the source code while the right side
shows the result of the program after compilation and execution.
// First Programming in C++
Whenever you see a line starting with “//” in the C++ program, it
indicates a comment line. They don’t have any effect on the course of the
program. however, the reason behind them is for the programming to make
some observation or explanations. It allows you to make a short description
of what the program is all about
#include <iostream>
Lines starting with # are directives for the preprocessor. Although they are
not normal code lines with expressions, however, are indications for the
compiler’s preprocessor. In the program above, the directive tells the
preprocessor to add the iostream to the standard file.
Using namespace std;
Every element in the standard C++ library is usually declared in a namespace.
Therefore, for one to access its functionality, you must declare use this
expression to do that.
Int main ()
This line indicates the beginning of the main function definition. The main
function is the starting point of any C++ programs and their execution begins
here. For any program, a pair of parentheses () always follow the word
“main” What differentiates a function from other types of expression is the
parentheses that follow the name.
cout << “Welcome to C++ Programming!”;
This line is a C++ statement. The cout is a standard output stream in C++,
which is followed by a sequence of characters enclosed in quotes. If you
observe clearly, the statement ends with a semicolon (;).
Return 0;
The return statement makes the main function (int main ()) to terminate.
This is very simple, right. Assuming you have to store millions of numbers,
can your brain accommodate it? Emphatically, No! However, a computer can
store much more than that and perform sophisticated mathematical
operations. A Variable is part of a memory that stores a determined value.
Every variable requires an identifier, which differentiates it from others. For
instance, in the example above, the variable identifiers include a, b, and
results. You can call the variable any name you like.
Identifiers
An identifier is valid if it has a sequence of one or more letters, underscore
character (_), or digits. However, there shouldn’t be any symbols,
punctuation marks or space when naming an identifier. The only valid
characters are letters, digits and underscore. Additionally, every variable
identifier must start with a letter. Besides this, you can also use an
underscore; however, in certain situations, they are reserved as specific
keywords.
When naming an identifier, another important thing to consider is that they
should not be keywords. Keywords are specific words used only by the
compiler.
The standard reserved keywords in C++ language include asm, auto, bool,
break, case, catch, char, class, const, const_cst, continue, default, delete, do,
double, dynamic_cast, else, enum, explicit, export extern, false, float, for,
friend, goto, if, inline, int, ling, mutable, namespace, new, operator, private,
protected, public, register, reinterpret_cast, return, short, signed, sizeof, static,
static_cast, struct, switch, template, this, throw, true, try, typedef, typeid,
typename, union, unsigned, using, virtual, void, volatile, wchar_t, while
Note – Like C language, the C++ language is case sensitive. This means that
when you write an identifier in capital letters, it is not equivalent to another
having the same name in small letters. For instance, the variable HOUSE is
not the same as using “house” or “House” as a variable. The three examples
are different identifiers.
** The values of the size and range of the data types depends on the
preprocessor of the system that the program is compiled. However, the above
table shows the values for a 32-bit system.
Variable Declaration
You cannot use a variable in C++ unless you declare it. When you hear of
variable declaration, it means stating the particular data type you want that
variable to be. the syntax for variable declaration involves writing the
particular data type and followed by a valid variable identifier. You must
adhere to the rule of variable number in order not to have issues when writing
your program.
For instance
In C++, these two are valid variables declared. The first one declares “ab” as
a variable of integer type while the second declares the word “newNumber”
as a variable type of float. Once these variables have been declared, you can
use them within the program. however, instead of declaring a different
variable of the same type on different lines, you can decide to put them on the
same line and separate them using a comma.
For example, if you were to declare a, b, c, d, and e as an integer, you can
declare them like this:
Int a, b, c;
Rather than
Int a;
Int b;
Int c;
Since you are new to the language, I will use an example to demonstrate with
a variable declaration in a program.
// Declaring Variable
#include <iostream>
using namespace std;
int main ()
{
int A, B;
int Outcome;
Output
84
Variable Scope
A variable in C++ can be in a global or local scope. When you declare a
variable within the body of the source code is it global; nevertheless, a local
variable is one declared within the body of a block or function. If you look at
our program above, you will observe that the variables were declared along
with the data type was declared at the beginning of the main function (int
main ()). Global variables can be referenced from anywhere in the program, it
does not matter if it is inside a function. However, local variables are limited
to enclosed braces {}. The diagram below is self-explanatory for you.
Variable Initialization
When you declare local variables, by default its value is undetermined.
However, you may decide to store a value when you are declaring the
variable. For this to happen, you would have to initialize the variable. There
are two ways of variable initialization in C++.
The first one involves appending and equal sign (=) followed by the value,
which the variable will initialize. For instance, I want to declare a variable
“A” of data type integer while initializing it to the value 5 at the moment.
This will be:
Int A = 5;
The second means of initializing variables is through a process called
“constructor initialization”, which involves enclosing the initial value
between parentheses (()). For instance,
Int A (0);
In C++, both ways of variable initialization are valid and acceptable.
Strings in C++ Programming
Variables with non-numerical value and longer than a single character are
known as a string. The C++ has its own standard library that allows strings
operation. Although it is not a fundamental data type, it does behave in a
similar fashion as data types.
To be able to use a string in C++, you have to include an additional header in
your program.
This is quite enough to understand string, as I will not dive deep into its
operation. With this, you can display a string with various characters.
Remember, you have to declare the variable with the string keyword (string
myName = “My Name is Johnbull Cosmos.”;)
Constants
By now you will understand what constants or literals are if you go through
the C programming in chapter two. It has the same operation in C++;
constants are used to express the value of a variable in the course of the
program. Remember our previous program where we declare A = 5. In this
situation, 5 is a literal constant. Literal constants are categorized as follows
Integer numerals
These numerical constant specify integer decimal values. To use a numerical
constant you don’t require any special character or quote attached to them.
Examples of integer numerals include
1176
45
-404
Floating-point number
These numbers have decimal or exponents. They include a decimal point or e
character or both attached together. For instance,
3.1578
2.25e23
16.5e-19
Arithmetic Operators
The variable b will contain 1 since that is the remainder when you divide 21
between 5.
Besides this, there are two additional operators known as the decrement (--)
and increment operators (++). These two operators can be used before
(prefix) or after (postfix or suffix) a variable. In as much as expressions such
as b++ and ++b have the same meaning; however, in a situation where the
result of the decrease or increase is evaluated in as a value in an outer
expression, the meaning will be different. In the scenario where the increment
operator is the prefix (++b), the value of the variable “b” is increased before
you evaluate the result of the expression
On the other hand, where the increment operator is the postfix (b++) the
value of the variable “b” is increased after the evaluation of the operation.
Does it sound confusing? Well, an example will make it clearer for you.
Example 1 Example 2
B=4; B=4;
C = ++B; C=++B
//A contains 4 while B contains 4 //C contains 3 while B contains 4
Does it make any sense now? Of course, it should be if you are not clear, here
is the explanation.
In the first example, the content of B is first increased before the value is
copied to A whereas in the second example, the value of B is copied A before
the value of B is increased.
Study the Program below, what do you think will be the output?
int main()
{
int i = 0;
while(i < 10)
{
cout << i++; //post increment
}
cout << endl;
i = 0;
while(i<10)
{
cout << ++i; //pre increment
}
return 0;
}
Logical Operators
There are three logical operators in C++, which are the conjunction (&&),
disjunction (||), and the negation (!) operators. You can also refer to them as
the AND, OR, and NOT operator.
The table below shows the AND and OR logical operators
A B A&&B A||B
True True True True
True False False True
False True False True
False False False False
Table for NOT
Logical Operator NOT
True False
False True
Relational Operators
The relational operator is used to evaluate a comparison between two values
or expression. The result of the relational operation is normally a Boolean
value, which can only be true or false (0 for true and 1 for false). The format
is as follows:
Operand1 (operational operator) operand2
The operands can be a literal or a variable. The following are the relational
operators in C++
Relational Description Meaning
Operators
== Equal to Returns true if both
operand 1 and 2 are
equal
!= Not Equal to Returns true if both
operands are not equal
> Greater than Returns true if
operand 1 is greater
than operand 2
< Less than Returns true if
operand 1 is less than
operand 2
>= Greater than or equal Returns true if
to operand 1 is greater
than or equal to
operand two, else it is
false
<= Less than or equal to Returns true if
operand 1 is less than
or equal to operand
two, else it is false
4 is equal to 6 = 0
4 is not equal to 6 = 1
4 is less than 6 = 1
4 is greater than 6 = 0
4 is not less than 6 = 0
4 is not greater than 6 = 1
Bitwise Operators
This operator is similar to the logical operators we just discussed. However, it
performs logical operations on bits. Unlike the logical operators, that use true
or false, the bitwise operators return the output as either 0 or 1.
Operator ASM Equivalent Description
& AND Bitwise AND
^ XOR Bitwise Exclusive OR
| OR Bitwise Inclusive OR
Assignment Operators
The function of this operator is to assign a value on the right-hand side to the
variable on the left. It uses the “=” as the operator in C++. You can also
combine assignment operators with the different operators mentioned so far
in this chapter. If you combine them, they form a composite or compound
assignment operator. Composite operators include +=, -=, *=, /=, >>=, <<=,
%=, |=, ^=, and &=.
Consider the following expression
Expression Meaning
Number1 += number2; Number1 = Number1 + number2;
b-= 10; b = b – 10;
cost *= profit + 2; cost = cost * (profit +1);
main()
{
int a, b, n1 = 0, n2 = 1, next;
cout << "Enter the number of terms of Fibonacci series you want"
<< endl;
cin >> a;
cout << "First " << a << " terms of Fibonacci series are :- " << endl;
for ( b = 0 ; b < a ; b++ )
{
if ( b <= 1 )
next = b;
else
{
next = n1 + n2;
n1 = n2;
n2 = next;
}
cout << next << endl;
}
return 0;
}
Depending on your input, the result will differ. Run the program and discover
what the output will look like.
C++ Capabilities
Considering the uniqueness of the C++ programming language, it has the
following capabilities
An object-oriented language supports aggregation, multiple
inheritance, and dynamic behavior.
It is highly portable
It supports operator overload to work naturally with user-defined
classes
It gives developers a whole lot of choices in terms of design and
coding.
It doesn’t require any graphic environment
It is compatible with C
C++ Limitations
It is difficult to debug when used for complex web application
It does have security
Normally used for specific platform application
It doesn’t support garbage collection
Doesn’t support built-in threads
It is not secure because it has friend function, pointer, global
variable
Chapter Five: SQL
Introduction
Structured Query Language (SQL) is a standard language designed for a
relational database management system to help manage data effectively. It is
a programming language precisely designed for the storage, retrieval,
managing, and manipulation of data relational database management system
(RDBMS).
It is hard to perform any database activity without using SQL because it is
supported by various prominent relational database systems such as Oracle,
SQL Server, and MySQL. Furthermore, some features available in the
standard SQL are implemented differently in various database systems.
IBM developed this query language originally in the early 1970s. Originally,
it wasn’t called SQL but SEQUEL (Structured English Query Language)
before it was changed to SQL. You are in for a wonderful adventure because
this aspect of this book will help you learn and understand the basics of SQL.
Basic Terms
What is Relational Database?
A relational database is a type of database categorized into tables with each
table relating to another within the database. It allows data to be divided into
smaller, logical, and manageable units for better performance and easier
maintenance. To relate one table to another, you need to create a common
field or key in a relational database system.
Definition Data
Data is a fact that relates to a particular object under consideration. For
instance, your name, weight, height, weights are unique to you. You can also
consider a file, image, or picture as data.
Definition Database
A database is a systematical collection of data. Through a database, you can
manipulate and manage data easily. For instance, your electricity supply has a
database to manage your billing, address, and other relevant information.
Another example is your famous Facebook account; it contains information
relating to your friends, messages, member activities, pictures, etc.
SQL Syntax
SQL Statements – These statements are simple and straightforward like your
normal English language. However, they have specific syntax. Don’t form
your own meaning when you see some of the common English words you are
conversant within this chapter.
An SQL statement comprises of a series of keywords, identifiers, etc. and
ends with a semicolon (;). The following is an example of a SQL statement:
SELECT stu_name, DoB, age FROM studentFile Where age > 20;
The statement may look clumsy but for better readability, you can rewrite it
in this format.
SELECT stu_name, DoB, age
FROM StudentFile
WHERE age > 20;
The purpose of the semicolon is to submit the statement to the database
server or terminates the SQL statement.
The first one capitalizes the keywords whereas the second isn’t capitalized. It
is better to write SQL keywords in uppercase in order to differentiate it from
other text.
SQL Comments
Similar to other programming languages, SQL comments are ignored and
provide quick explanations concerning the SQL statements. You can either
use a single-line or multi-line comments when writing comments in SQL.
The two examples below will distinguish both comment writing formats.
--Select all the students
SELECT *FROM studentFile;
To write a multi-line comment, you use the /* with the statements followed
by the */.
/* Select all the students
whose age is greater than 20*/
SELECT *FROM studentFile
WHERE age > 20;
Database Creation
Before you can work with data, the first thing to do is to create a database. I
am assuming you have installed the SQL Server or have MySQL in your
system. Furthermore, ensure to allow every necessary privilege needed.
There are two ways of creating a database
Using the simple SQL query
Using MySQL
Simple SQL Query
The syntax for creating a database in SQL is
CREATE DATABASE databaseName;
For the examples illustrated earlier, to create the table, we have to use:
CREATE DATABASE studentFile;
Note: You can also use CREATE SCHEMA rather than using CREATE
DATABASE to create a database. Additionally, creating a database doesn’t
make it available for use. To select the database, you have to select the
database using the USE statement. For instance, the USE studentFile;
command will set the StudentFile database as the target database.
MySQL Database Creation
I will use a command line tool to create a database in MySQL.
Step 1: Invoking the MySQL command-line tool
To do this, you have to log into your MySQL server. You have to log in as a
root user and enter your password when asked. If everything goes right, you
will be able to issue SQL statements.
Step 2: Creating the database
To create the database “studentFile”, you have to execute the following
command.
mysql> CREATE DATABASE studentFile;
If the database was successful, you will see – Query OK, 1 row affected (0.03
sec). However, if the database already exists, an error message will display.
Therefore, to avoid such situation, you can include an optional clause – IF
NOT EXISTS. To apply it to the example, it will be written as:
mysql> CREATE DATABASE IF NOT EXISTS studentFile;
Tip – in order to see all the list of existing databases when using MySQL
server, you can use the “SHOW DATABASES” keyword to execute it.
Besides the data type, there are constraints used in the code. Constraints are
rules defined concerning the values permitted in columns. The following
constraints were mentioned.
The PRIMARY KEY constrains, which marks the corresponding
field as the primary key for the table
The NOT NULL constraints, which make sure fields cannot accept
an unacceptable value
The AUTO_INCREMENT attribute, which automatically assigns a
value to a field left unspecified. It increases the previous value by
1 and only available for numerical fields.
The UNIQUE constraint ensures every single row contains a
unique value in the table
In a similar fashion, you can use the IF NOT EXIST statement we used when
creating a database to overwrite an existing table. This is important as it
avoids any already existing table. Alternatively, if you want to display
available tables, you can use the SHOW TABLES statement.
CREATE TABLE IF NOT EXISTS studentRecords (
id INT NOT NULL PRIMARY KEY AUTO_INCREMENT,
Studname VARCHAR(40) NOT NULL, DoB,
phoneNum VARCHAR(25) NOT NULL UNIQUE
);
Constraints In SQL
As the name implies, it is a restriction or limitation imposed on a column (s)
of a table in order to place a limitation on the type of values the table can
store. They provide a better mechanism to retain the reliability and accuracy
of the data contained in the table. We have several categories of constraints,
which includes:
NOT NULL Constraint – This statement states that NULL values will not
be accepted at the column. What it means is that a new row cannot be added
in a table without the inclusion of a non-NULL value for such a column.
For instance, the statement below creates a table “studentRecords” with four
columns and three of these columns (id, Studname, and phoneNum) do not
accept NULL Values.
CREATE TABLE studentRecords (
id INT NOT NULL,
Studname VARCHAR(30) NOT NULL,
DoB DATE,
phoneNum VARCHAR(15) NOT NULL
);
Tip: A null value is not the same as blank, zero (0), or a zero-length character
string. The meaning of a NULL is that there hasn’t been any entry made in
that field.
PRIMARY KEY Constraint – This classifies a column (s) with
values that distinctively recognize a row in the table. You cannot
have two rows simultaneously in a particular table having the same
value for its primary key. The example below shows a SQL
statement creating a table named “studentRecords” and identify the
id column as the primary key.
CREATE TABLE studentRecords (
id INT NOT NULL PRIMARY KEY,
Studname VARCHAR(30) NOT NULL,
DoB DATE,
phoneNum VARCHAR(15) NOT NULL
);
UNIQUE Constraint – if you want to restrict a column (s) to
contain unique values in a table, the UNIQUE statement is used.
While the PRIMARY KEY and UNIQUE constraint enforce
uniqueness in a table; however, the UNIQUE constraint is used
when your goal is to enforce the exclusivity on a particular column
(s). I will use our previous example to specify the phone column as
unique. With this, the phone column won’t allow duplicated
values.
CREATE TABLE studentRecords (
id INT NOT NULL PRIMARY KEY,
Studname VARCHAR(30) NOT NULL,
DoB DATE,
phoneNum VARCHAR(15) NOT NULL UNIQUE,
country VARCHAR(30) NOT NULL DEFAULT 'England'
);
FOREIGN KEY Constraint – This particular kind of constraint
is a column (s) used to set up and implement a relationship among
data in two different tables.
CHECK constraint – The purpose of this statement is to restrict
values in a column. For instance, the range of student age column
can be restricted by creating CHECK constraint, which allows
values only 16 to 45. This hinders ages entered from exceeding the
age range. Here is an example to illustrate it.
CREATE TABLE studentRecords (
stu_id INT NOT NULL PRIMARY KEY,
stu_name VARCHAR(55) NOT NULL,
stu_date DATE NOT NULL,
age INT NOT NULL CHECK (age >= 16 AND age <= 45),
dept_id INT,
FOREIGN KEY (dept_id) REFERENCES departments(dept_id)
);
If you were to display the output of this table, it will look like this
id FullName Age Sex PhoneNum
1 Donald 30 Male 0722-022569
Williamson
2 Jefferson 45 Male 0252-027948
Peterson
3 Mariah 50 Female 0722-457906
Lawson
Perhaps, you only need certain information in the table, you use specific
columns. Assuming we want to select only the id, FullName, and sex. It will
look like this.
SELECT id, FullName, Sex
FROM studentRecords;
After executing this statement, the output will be
id FullName Sex
1 Donald Male
Williamson
2 Jefferson Male
Peterson
3 Mariah Lawson Female
The statement below will fetch all the record of the student with id 4
SELECT *FROM studentRecords WHERE id = 4;
The output will be:
id FullName Age Sex PhoneNum
4 Jackson Fred 32 Male 0721-487924
You can combine certain operates with the “WHERE” clause. The table
below summarizes the important operators used in SQL.
Operator Description Example
= Equal WHERE id = 4
> Greater than WHERE age > 30
< Less than WHERE age < 25
<= Less than or equivalent to WHERE price <= 900
>= Greater than or equivalent to WHERE age >= 15
LIKE Simple pattern matching WHERE name LIKE 'Dav'
IN Check whether a specified value WHERE Country IN
matches any value in a list or ('BRAZIL', 'SWEDEN')
subquery
BETWEEN Check whether a specified value is WHERE age BETWEEN 3
within a range of values AND 5
The OR Operator
This operator combines two different conditions; however, if one or both
conditions are true, it returns true. Assuming you want the record of students
whose age is greater than 40 or the Dept_No is equal to 0104.
SELECT *FROM studentRecords
WHERE age > 40 OR Dept_No = 0104;
The output will be:
id FullName Age Sex PhoneNum Dept_No
2 Jefferson 45 Male 0252- 0102
Peterson 027948
3 Mariah 50 Female 0722- 0103
Lawson 457906
4 Jackson 32 Male 0721- 0104
Fred 487924
Furthermore, you can combine the “AND” and “OR” operator to create
compound expressions. Consider the statement below.
SELECT *FROM studentRecords
WHERE age > 40 AND (Dept_No = 102 or Dept_No=103);
Format:
UPDATE tableName
SET column1Name = value1, column2Name = value2,…
colunmNamen = valueN
WHERE condition;
To update the student record of Venus Sean to Venus Williams Sean, the
statement will be
UPDATE studentRecords SET FullName = “Venus Williams Sean”
WHERE id =5;
SQL DELETE
Finally, you have learned how to insert, select, and update information in a
table. However, it is important to know how to delete a specific field or entire
table especially if the table has fulfilled its purpose.
Format:
DELETE FROM table_name WHERE condition;
Using the table below, let us delete some records from the student’s record
created.
id FullName Age Sex PhoneNum Dept_No
1 Donald 30 Male 0722- 0101
Williamson 022569
2 Jefferson 45 Male 0252- 0102
Peterson 027948
3 Mariah 50 Female 0722- 0103
Lawson 457906
4 Jackson 32 Male 0721- 0104
Fred 487924
5 Venus Sean 38 Female 0787- 0105
972853
6 Merkel 36 Female 0978- NULL
Hassan 216597
However, to delete the entire data in a table, there isn’t any need to use the
WHERE clause. To delete all records in the “studentRecords” table, you have
to use the statement below.
DELETE FROM studentRecords;
Chapter Six: Introduction to Java
Programming
Welcome to your fifth programming course in this book. Indeed, you have
progressed beyond your expectation. Did you think you could do it at the
beginner? Nobody is born a programmer rather by learning and putting it to
practice, they become good at it.
Welcome to Java Programming. I will introduce you to Java in its simplicity.
Java is one of the most interesting and practicable programs to learn as a
beginner. At the end of this chapter, you will become a professional computer
programmer.
As I always tell beginners, programming is easy. At first, many consider Java
as a hard language to understand but after familiarizing themselves with the
environment, they discover it is quite easy to learn. It doesn’t matter your
programming experience or level, this chapter was written putting various
things into consideration. As you expand your programming knowledge, you
will discover that you will be a top-notch programmer in all areas.
In spite of the numerous programming languages in the world, Java is one of
the languages in high demand. If you dedicate your time into studying the
environment, you are literally setting yourself into a fast-growing career in
the next few years. Java programming skills are sought after because of its
flexibility, readability, and simplicity. Presently, if you are a Java
programmer or developer in the United States of American, you will be
earning nothing less than $85k annual salary. Do you still think Java
programming is worth learning?
Pre-requisite for Learning Java
You must know the basics of how to use a computer system. However, if you
are a beginner to programming, then you need to understand the fundamental
to programming. If you already know programming languages like C, C++ or
any object-oriented language, then Java should be an easy language for you
to learn.
Encapsulation
From the name, you can have an idea of what encapsulation entails.
Encapsulation in a layman term is a method that binds the programming code
along with data it operates while keeping them safe from exterior
interference. An object is formed when these data and code are connected
with each other. This object can be private or public; if it is private, the data
or code will be inaccessible by any program that exists out the object.
However, if it is public, it can be accessible by other programs even if they
are not within the object.
Polymorphism
Another important concept of Java Programming is polymorphism, which
involves creating a particular interface for several methods. The significance
is that it reduces program complication by permitting the same interface.
Inheritance
This concept involves an object receiving the same features or properties of
another object that supports it. For instance, you have a watermelon, which is
of the classification of watermelon. It also belongs to a fruit class that is part
of a larger class known as food. This food class has features that make it
nutritious and edible. Additionally, the fruits can be sweet and juicy.
Therefore, combining these features and other things makes up the
watermelon.
Output
Hello World, This is my first programming practice in java.
Explanation
public class MyFirstJaveProgram {
this is the beginning of a java program. All java application must have at least
a class definition, which comprises of the class keyword accompanied by the
class name. From the first line, you can see that the class is public
public static void main(String[] args){
This statement makes the main method to be “public”. What it means is that
you can call the method from outside the class. The void in the statement
signifies that it doesn’t return anything whereas main is a method name. It is
the starting point where the program begins execution. Additionally, the
(String[] args) is a command line argument
System.out.printlin (“Hello World, This is my first programming practice in
java.”)
This statement prints out the content of what is in the quotes to the console
while inserting a newline.
Variables
I believe you know what a variable is as you have gone through various
programming languages in this book. The variable is allocated a value during
the program. Its value changes in the course of the program. For instance,
int number1 = 12;
In this example, number1 is a variable name where 12 is the value assigned to
it. On the other hand, int is a data type that declares “number1” as a variable.
Types of Variables
Variables are of three types in Java.
Local Variable
You declare these variables inside the method of a class. Furthermore, the
scopes of these variables are limited to the method. Their values cannot be
changed and accessed outside the method. From the example below, the
instance variable is declared having the same local variable name. The
essence of this is to show the scope of the local variable scope. Study the
program properly because missing any step here will affect you later.
public class VariableExa {
// I want to declare the instance variable at this point
public String myVar="instance variable";
// declaration of instance variable done
public void myMethod(){
// Here I am declaring our local variable
String myVar = "Inside Method";
System.out.println(myVar);
}
public static void main(String args[]){
// This area creates the object
VariableExa obj = new VariableExa();
/* we call the variable name, which changes myVar value.
* Furthermore, myVar will be displayed after
* the method call, to indicate that the
* scope of the local variable is restricted to only the method.
*/
System.out.println("Calling Method");
obj.myMethod();
System.out.println(obj.myVar);
}
}
Static Variable
Some programmers refer to it as a class variable because of its association
with the class. For instance, if you create four different objects; however,
these objects have the same class with access to the static variable, the static
variable will be common for all object. In order words, an alteration to the
variable through the use of a single object will literally imitate others when
accessed through the other objects. Consider the program below that
illustrates the use of a static variable.
Instance Variable
This variable is the opposite of the static variable because every single object
within a class contains its own duplicate, unlike the static variable that
contains the same object. From the example below, the value of the instance
variable (obj2) is changed and when displayed with other objects, others
remained unchanged, unlike the obj2.
System.out.println(obj.InstanceVar);
System.out.println(objA.InstanceVar);
System.out.println(objB.InstanceVar);
Now, observe the difference between the static variable and the instance
variable. Did you notice any major difference? Let us move into something
more important – data types.
Data Types
The meaning of data type is the same whether it is Java, C, C++, or SQL. The
data type defines that particular value a variable can accommodate. For
instance, a variable of integer data type has the capacity of only
accommodating integer values. Nevertheless, data types are of two types in
Java. These are primitive and non-primitive. Notwithstanding, my focus in
this book is on the primitive data types. For clarity purpose, you should know
that non-Primitive data types include strings and arrays.
Java Programming Primitive Data Types
Generally, Java has eight primitive data types and these include int, short,
Boolean, char, long, byte, double and float. These data types are the same
irrespective of the operating system you are using.
Int
This data type is used to hold integer variables and ranges from
-2,147,483,648 up until 2,147,483,647. It has a default size and value of 4
bytes and 0 respectively. The example below shows the variable “number1”
declared as an integer data type and printed out.
class DataTypeExample {
public static void main(String[] args) {
// Declaration of variables
number1 = 1250;
System.out.println(number1);
}
}
Outcome:
1250
Byte
A byte data type can only hold numbers between -128 and 127. It has a data
size and value of 1 byte and 0 respectively. Study the program below.
class DataTypeExample {
public static void main(String[] args) {
// declaration of NewNum as byte
byte NewNum;
NewNum = 80;
System.out.println(NewNum);
}
}
Output:
80
What will be the result now? If your answer is 180, you are obviously wrong.
Are you surprised? Do you remember the byte data type range is between
-128 and 127? Therefore, if you execute the above program, you will get a
type mismatch error because 180 is beyond the range data type.
Short
In terms of size, it is greater than the byte data and has a default size of 2
bytes. It has a data range of 32,768 to 32767.
class DataTypeExample {
public static void main(String[] args) {
// Declaration of the variable
short number1;
number1 = 18000;
System.out.println(number1);
}
}
The output will be:
18000
Long
You can use this data type when the int data type isn’t big enough to
accommodate the value you want to use. It ranges from
-9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 and has a size of
8 bytes.
class DataTypeExample {
public static void main(String[] args) {
// declaration of the variable to demonstrate long data type
long number1= -48972698741L;
System.out.println(number1);
}
}
Output
-48972698741
Double
This holds up to 15 decimal numbers and has a size of 8 bytes.
class DataTypeExample {
public static void main(String[] args) {
//declaration of variable
double number1 = -789874437.9d
System.out.println(number1);
}
}
What will be the Output:
-4.145898371E7
Char
This holds characters and has a size of 2 bytes.
class DataTypeExample {
public static void main(String[] args) {
// declaration of variable Myname as char
char Myname = 'Johnson';
System.out.println(Myname);
}
}
Output
Johnson
Boolean
This either holds true or false value.
class DataTypeExample {
public static void main(String[] args) {
// performing Boolean operation using true and false
Boolean light = True;
System.out.println(light);
}
}
The Output will be:
True
Float
This holds 6 to 7 decimal number and has a size of 4 bytes.
class DataTypeExample {
public static void main(String[] args) {
float number1 = 20.70f;
System.out.println(number1);
}
}
Output
20.70
Summary of primitive data types
If you want to store whole numbers, you can use long, short,
byte, and int data types
char is used for storing letters
double and float for fractional numbers
Boolean for variables that hold true or false
Operators in Java Programming
This section describes available operators you can use in the course of your
coding. You can use them to manipulate variables or create complex
programs. Normally, you can use these operators to compare, modify, and
control data within the Java environment. The basic operators in Java
include:
Arithmetic Operators
You are already familiar with these operators and they include addition (+),
subtraction (-), multiplication (*), division (/), and modulo (%). I will use a
simple program to illustrate these operators.
public class ArithmeticOperator {
public static void main(String args[]) {
// declaration of profit and loss as integer to perform the arithmetic
operation
int profit = 250;
int loss = 70;
Assignment Operator
These operators include =, +=, -=, *=, /=, and %=
Income=expenses this assigns the value of the variable expenses to Income
Income +=expenses is equivalent to Income = Income + expenses
Income -=expenses is equivalent to Income = Income – expenses
Income*=expenses is equivalent to Income = Income * expenses
Income/=expenses is equivalent to Income = Income/expenses
Income%=expenses is equivalent to Income = Income % expenses
Consider the program above to illustrate the use of assignment operators
public class AssignOpe {
public static void main(String args[]) {
int income = 10;
int expenses = 20;
expenses += income ;
System.out.println("+= Output: "+expenses);
expenses = income ;
System.out.println("= Output: "+expenses);
expenses -= income ;
System.out.println("-= Output: "+expenses);
expenses /= income ;
System.out.println("/= Output: "+expenses);
expenses *= income ;
System.out.println("*= Output: "+expenses);
expenses %= income ;
System.out.println("%= Output: "+expenses);
}
}
+= Output: 20
= Output: 10
-= Output: 10
/= Output: 10
*= Output: 100
%= Output: 0
Logical operator
These are used for conditional statements and loops to evaluate a condition.
These operators are &&, !, and ||.
Operator Meaning Example
! Logical Not. This If a=5 then, the
evaluate true only if expression! holds
the operand is 0 true.
&& Logical AND. It If a =4 and b = 2; the
returns true only expression ((a==4)
when all the operands && (a<4)) equals to
are true. 0.
|| Logical OR. This If a =4 and b = 2; the
evaluates to true when expression ((a==4)
one operand returns && (a<4)) equals to
true 1.
Consider the program above.
Conclusion
There are other operators available in Java; however, with the
aforementioned operators, you can start programming. Finally, you have
gotten to the end of the basics of Java programming. Don’t stop here, put to
practice everything you have learned and considered moving to advanced
programming.
Chapter Seven: JavaScript Programming
for Beginners
If there is anything I want you to hold at the end of this programming guide
for JavaScript is the fact that:
JavaScript is the HTML and web language
It is easy to Learn
If you can do that, then at the end, you will smile your way to programming
for the web. However, your speed in learning JavaScript and other
programming language is very dependent on you. If you find yourself
struggling, don’t feel demoralized rather take a break and reread the material
after you have settled down. Remember, this chapter gives you the basics of
JavaScript as a beginner to familiarize yourself with the language.
Introduction
This JavaScript guide is written with the intention to help both beginners and
professionals understand the programming language for the web more
efficiently. JavaScript is a solution aimed at performing various actions
dynamically. The JavaScript translator, which is rooted in the web browser
such as Firefox, Google Chrome, Internet Explorer, Safari, etc., allows the
interpretation of the JavaScript code.
JavaScript is an object-oriented scripting language, which is lightweight and
works in cross-platform such as Mack, Linux, or Windows. If you want to
create an interactive website for users, the place of JavaScript cannot be
overemphasized.
What is JavaScript?
It is a scripting language created in 1995 by Netscape as a means of
validating forms while offering interactive content for websites. The language
has evolved over time with it being used by various web browsers.
Variables in JavaScript
Variables shouldn’t be new if you went through Chapter two to Chapter six
of this book. In a layman term, a variable is a memory location designed to
store different values and assigned with a name. JavaScript uses the “var”
keyword, accompanied by the variable name. For instance, to a name as a
variable, you will use the statement below.
var exam = 50;
var test = 12;
var score = exam * test;
In the example above, exam, test, and score are variables given values with
the value stored. We can perform various operations in JavaScript including
multiplication, subtraction, addition, subtraction, and division. Variables and
values can be declared as a number, string, or letter.
var name = “insert your name”;
var number = ‘45’;
From the example, you can enclose string with a single or double quote
because they work exactly the same way.
JavaScript Identifiers
Every variable in JavaScript must have a unique name, which is used to
identify it. These unique names are called identifiers. Identifiers have certain
rules, which include:
Every identifier must begin with a letter
They can contain digits (0-9), letters (a-z), dollar signs ($), and
underscores (_)
Reserved words are not accepted
Variable names are case sensitive
An identifier can begin with a dollar sign or underscore.
The program below demonstrates the use of data type in JavaScript. The first
one shows a JavaScript program that shows the summation of two floating
numbers (test and exam) while the second one illustrates the use of Boolean
data type.
<html>
<head>
<script language="javascript">
function showAlert()
{
var test=22.50;
var exam=50.50;
var score=0;
score=test+exam;
document.write(" score= "+score);
document.write("\t\tHello\nworld!\n");
document.write('\nWelcome to JavaScript');
}
</script>
</head>
<body>
<script language="javascript">
showAlert();
</script>
</body>
</html>
The program below illustrates the use of Boolean expression. First, I allocate
the value “0” to the variable “number.” Then the user is prompted to enter a
number, which must be within the range of 1 and 500. Nonetheless, If the
user entered a number above the stated range (500), a message will be
displayed on the screen indicating an error.. However, if the number falls
within the 500 range, it will determine if the figured inputted is either equal
or greater
<html>
<body>
<script type="text/javascript">
var number=0;
number=prompt("Enter a number");
document.write("Your entered number is :"+number);
if (number>=1 && number<10)
document.write("Your entered number is greater than 1 and less than
10");
else if(number>=10 && number<20)
document.write("Your entered number is greater than 10 and less than
20");
else if(number>=20 && number<30)
document.write("Your entered number is greater than 20 and less than
30");
else if(number>=30 && number<40)
document.write("Your entered number is greater than 30 and less than
40");
else if(number>=40 && number<100)
document.write("Your entered number is greater than 40 and less than
100");
else if(number>=100 && number<=500)
document.write("Your entered number is greater than 100 or less than
500");
else
document.write("You did not enter any number!")
</script>
</body>
</html>
Operators in JavaScript
Operators are functions with arithmetic, bitwise or logical property.
JavaScript also has its own operators to perform various operations. In this
unit, I will explore the basic operators you can use as a beginner in
JavaScript.
Arithmetic Operators
Operators Meaning
+ Addition
- Subtraction
/ Division
* Multiplication
= Assignment
% Mod
-- Decrement
++ Increment
You should be conversant with some of these operators if you have gone
through this book. However, I am not going to explain anything but illustrate
each operator using a JavaScript program.
Addition
var number1 = 105;
var number2 = 25;
var total = number1+number2; //total = 130
Subtraction
var number1 = 105;
var number2 = 25;
var total = number1-number2; //total = 180
Multiplication
var number1 = 105;
var number2 = 25;
var total = number1*number2; //total = 2625
Division
var number1 = 105;
var number2 = 25;
var total = number1/number2; //total = 4.2
Mod
var number1 = 105;
var number2 = 25;
var total = number1%number2; //total = 5
Assignment
var number1 = 105;
var number2 ;
number2 = number1; //total = 105
Increment
var number1 = 105;
var number2 = number1++; // number2 = 106
Decrement
var number1 = 105;
var number2 = number1--; // number2 = 104
String Operators
The string operator uses the sign “+” to concatenate two or more strings.
var FirstName = “Fname”’;
var LastName = “Lname”;
var FullName = FirstName + “” + LastName;
JavaScript Framework
Take a moment and consider creating a web application and websites like
constructing a house. In building a house, you can decide to create every
material you need to start the house from scratch before building without any
plans. This will be time-consuming and won’t make much sense. One thing
you may likely do is to buy pre-manufactured materials such as bricks,
woods, countertops, etc. before assembling them based on the blueprint you
have.
Coding is like taking it upon yourself to build a house. When you begin
coding a website, you can code all areas of the site from scratch without.
However, there are certain website features, which gives your website more
sense by applying a template. Assuming you want to buy a wheel, it will
make to look for one that you can reinvent. This is where JavaScript
Frameworks come to the scene.
JavaScript Framework is a collection of JavaScript code libraries, which
gives website developers pre-written JavaScript codes to use for their routine
programming tasks and features.
You can also refer to it as an application framework, which is written in
JavaScript where the developers can manipulate the functions of these codes
and reuse them for their own convenience. They are more adaptable for
website designing, which is why many developers use them in building
websites.
Getting Started
Before starting this lesson, you should have the following:
PHP and MySQL installed
Web Server (Apache)
With these two programs, you can successfully write and execute PHP codes.
You can purchase an inexpensive hosting plan that supports MySQL and
PHP. However, if you want to save some cash, you can decide to install it on
your system. To do this, you have to install WAMP server on your machine
for Windows users. After the installation, you can access it through
http://localhost in your browser. Ensure you have this set up before starting
this course.
PHP Syntax
When I started, I indicated that PHP codes are executed on the server-side.
However, every PHP statement begins with <?PHP while ending with ?>.
Let us begin with a simple program. You can copy and paste the program
below using any text editor before saving it with the file name – index1.php
I named the file to “index1.php” because some root folder already has an
index filename as shown in the image below.
<html>
<head>
</head>
<body>
<?php
/* This line contains a comment
Which span to
several lines */
//This comment is a line comment
</body>
</html>
We first declare variable1 with the value 280. However, the second is a string
variable with value as “PHP Programming”
It is important to note that every statement n PHP ends with a semicolon. You
will get an error whenever you don’t include a semicolon to indicate the
ending of a statement.
Output
Strlen () function
Perhaps you want to determine the string length of a word or sentence, the
strlen function is what you need. Consider the example below.
<?php
echo strlen(‘‘Today is the best day of your life. Programming is a
lifelong skill and PHP is all your need’’);
?>
The outcome will be the string length of the text including the signs, space,
characters). In this situation, the result will be 92 as shown below.
Assignment operators
Operator Examples Large notation
%= p%=q p=p%q
*= p*=q p=p*q
.= p.=q p=p.q
/= p/=q p=p/q
+= p+=q p=p+q
= p=p p=q
-= p-=q p=p-q
Logical Operators
Operator Description Example
! not p=9
q=9
!(p==q) returns false
&& and p=9
q=9
(p < 10 && q> 1) returns true
|| or p=9
q=9
(p==5 || q==5) returns true
Arithmetic Operators
Operator Description Example Result
+ Addition a=8 13
a+5
– Subtraction a=17 3
20-a
/ Division a = 40 20
40/2
* Multiplication a=7 35
a*5
++ Increment a=9 a=10
a++
-- Decrement a=14 a=13
a--
% Modulus (division 56%6 2
remainder)
Comparison Operator
Operator Description Example
If Statement
The statement is required to execute a line of code as far as the condition
stated is true. Consider the example below.
<?php
$number= 23;
if($number='23')
echo "Wake up! Time to begin Your Programming lesson.";
?>
In the statement above, we first declare allocate the value 23 to the variable
“number”. The if statement now evaluates if the variable “number” is equal
to 23 since it is true, it will return:
It doesn’t work on string alone but you can also use it on number operations.
Switch Statement
The statement allows you to change the course of the program flow. It is best
suited when you want to perform various actions on different conditions.
Consider the example below.
<html>
<body>
<?php
$a=2;
switch ($a)
{
case 1:
echo 'The number is 10';
break;
case 2:
echo 'The number is 20';
break;
case 3:
echo 'The number is 30';
break;
default:
echo 'There is no number that match';
}
?>
</body>
</html>
Output:
Explanation
In the example above, we declare the variable “a” to be 3. The switch
statement has some block of codes, with case or default. If the value of the
case is equivalent to the variable $a, it will execute the statement within that
line and then break. However, if the value of the case is not equivalent to any
of the variable, it will break from the case before executing the default code
block.
Conclusion
PHP language isn’t restricted to professional web browsers alone. You don’t
have to be an IT administrative professional to learn it. Similar to any
scripting language, it may seem complicated at the first time; however, if you
preserver, you will discover it is an interesting language to learn. Learning
PHP programming is the perfect way of understanding the server-side world.
Writing PHP code is not something intimidating if you start from the
foundation as I have done in this book. PHP language is one of the languages
you don’t need anyone to teach you as long as you are ready to learn
everything. In this book, you have learned everything you need to get your
environment ready, variables, conditional statements, and much more.
Chapter Nine: Python Programming
Language
Introduction
Python Language is one of the easiest and straightforward object-oriented
languages to learn. Its syntax is simple, thereby making it simple for
beginners to learn and understand the language with ease. In this chapter, I
will cover several aspects of the Python programing language. This
programming guide is for beginners who want to learn a new language.
However, if you are an advanced programmer, you will also learn something.
Guido Van Rossum developed the Python language but the implementation
began in 1989. Initially, you could have thought, it was named after the
Python snake; however, it was named after a comedy television show called
“Monty Python’s Flying Circus.”
Features of Python
There are certain features that make the python programming language
unique among other programming languages. The summary is displayed in
the diagram below.
1. Easy to learn – Because python is a high-level and expressive
language, it is easy for everyone – including you to learn and
understand irrespective of their programming level – beginners to
advanced programming
2. Readable – It is quite easy to read the language
3. Open source – The language is an open-source language
4. Cross-platform – This means it is available and you runnable on
different operating systems including UNIX, Linux, Windows,
Mac, etc. This has contributed to its portability.
5. Free – The language is downloadable without paying anything.
Furthermore, not only can you download it, you can it for various
applications. The software is distributable freely.
6. Large standard library – Python has its standard library, which
contains various functions and code, which you can add to your
code.
7. Supports exception handling – Most programming languages
have this exception handling feature. However, an exception is a
situation that takes place in the course of program execution and
has the tendency to disrupt the flow of the program. With python
exception handling feature, you can write less error code while
testing various situation that may lead to an exception in the future.
8. Memory management – The language also supports automatic
memory management, which means it clear and free memory
automatically. There is no need for clearing the memory on your
own when you remember.
Uses of Python
Most beginners before choosing to learn a programming language first
consider what the uses of such language are. However, there are various
applications of the python language in a real-world situation. These include:
1. Data Analysis – You can use python to develop data analysis and
visualization in the form of charts
2. Game development – Today, the game industry is a huge market
that yields billions of dollars per year. It may interest you to know
that you can use python to develop interesting games.
3. Machine learning – We have various machine learning
applications that are written using the python language. For
instance, products recommendation in websites such as eBay,
Flipkart, Amazon, etc. uses a machine-learning algorithm, which
recognizes the user’s interest. Another area of machine learning is
a voice and facial recognition on your phone.
4. Web development – You didn’t see this coming. Well, web
frameworks such as Flask and Django are based on the python
language. With Python, you can write backend programming
logics, manage database, map URLs, etc.
5. Embedded applications – You can use python to develop
embedded applications
Launching PyCharm
For windows users, after installing the .exe file, you will see the PyCharm
icon on the desktop depending on the option you selected during installation.
You can also go to your program files > Jetbrains >PyCharm2017 and look
for the PyCharm.exe file to launch PyCharm.
Comments in Python
If you observe from the first line, I began with “#” whenever you see that it is
a comment and in Python, it doesn’t change the program outcome. Comments
are very important because it helps you to easily read the program by
providing further explanation of the codes in English for everyone to
understand.
Comments can be written in two ways in Python. This could be single or
multiple line comments. The single-line comment uses the #, which is an
example of the previous code. However, the multiple line comment uses three
single quotes (''') at the beginning and end respectively.
'''
Example of multiple line comment
'''
Let me use a real example to explain both the single and multiple line
comment.
'''
Sample program to illustrate multiple line comment
Pay close attention
'''
print("We are making progress")
Multiple Assignment
You can also allocate several variables to a single expression in python.
Consider the example below:
Profit = returns = yields = 35
print (Profit)
print (yield)
print (returns)
Output
35
35
35
c = “Welcome”
d = “Home”
print (c + “ “ + d)
Output
112
Welcome Home
Numbers
When working with numbers, python supports floats, integers, and complex
numbers. Float numbers are those with decimal points such as 9.9, 4.2, 42.9,
etc. An integer is the opposite of float because it does not have a decimal
point attached to it. For instance, 3, 35, 89, etc. however, a compound
number contain an imaginary and real part such as 7+10j, etc.
Let’s demonstrate the use of numbers in a python program
# Python program to show how we can use numbers
Strings
This is a series of characters enclosed within a special character. In Python,
you have the option of using a single or double quote to represent a string.
There are various means of creating strings in python.
You have the option of a single quote ‘
You can use a double quote ”
You can use a triple-double quotes “””
# Ways of creating strings in Python
str = 'single string example'
print(str)
# multi-line string
str3 = """ Triple double-quote string"""
print(str3)
Tuple
Tuple works like a list but the difference is that in a tuple, the objects are
unchangeable. The elements of a tuple are unchangeable once assigned.
However, in the case of a list, the element is changeable.
In order to create tuple in python, you have to place all the elements in a
parenthesis () with a comma separating it. Let me use an example to illustrate
tuple in python.
# tuple of strings
bioDate = ("John", "M", "Lawson")
print(bioData)
If Statement
The statement prints out a message if a specific condition is satisfied. The
format or syntax is as follow:
If condition:
Line of codes
flag = True
if flag==True:
print("Welcome")
print("To")
print("Python Programming")
Output
Welcome
To
Python Programming
Output
number1 is less than 290
If-else statement
in our previous example, we only test a particular condition, what if you want
to test two different conditions. That is where the “if-else statement” comes
to play. In Python, the statement executes a particular statement if it is true
but if it's not true, it executes the other statement.
Syntax
If conditions
Statement1
Else
Statement2
number1 = 180
if number1 > 290:
print("number1 is greater than 290")
else
print (“number1 is less than 290”)
Output
number1 is less than 290
Number1 = 15
if number1 % 4 == 0:
print("the Number is an Even Number")
else:
print("The Number is an Odd Number")
Output:
The Number is an Odd Number
Bonus Programs
# Program to display the Fibonacci sequence depending on the
number the user wants
public:
int p;
ab(int p) {
p = p;
}
};
main() {
ab c(5);
cout<<c.a;
}
A. Garbage
B. 5
C. Compile error “a” declared twice
D. Error at the statement a = a;
main()
{
int const a = 8;
p++;
printf(“%d”,p);
}
A. 6
B. 9
C. Runtime error
D. Compile error
Q2 – determine the program
#include<stdio.h>
main()
{
char p[]="welcome", q[]="welcome";
if(p==q){
printf("equal strings");
}
}
A. No output
B. Unequal strings
C. Equal string
D. Compilation error
Q3 - Consider the code snippet below, choose the right output.
#include<stdio.h>
main()
{
int p = 5, q = 3, r = 4;
printf("p = %d, q = %d\n", p, q, r);
}
A. compile error
B. p=5, q=3
C. p=5, q=3, 0
D. p=5, q=3, c = 0
Q4 - determine the output of the program
#include<stdio.h>
main()
{
int p = 1;
double q;
float r = 1.3;
q = p + r;
printf("%.2lf", q);
}
A. 2.3
B. 2.0
C. 2.30
D. Error
Q5 – determine the output
#include<stdio.h>
main()
{
enum { Germany, is=9, Excellent };
printf("%d %d", Germany, Excellent);
}
A. Compile error
B. 0 1
C. 0 2
D. 0 8
Q6 – determine the output of the program
#include<stdio.h>
main()
{
char p = 'B'+265;
printf("%c", p);
}
A. Compile error
B. Overflow error during runtime
C. B
D. A
Q7 – determine the output of the program
#include<stdio.h>
main()
{
short unsigned int a = 0;
printf("%u\n", a--);
}
A. 65568
B. 32789
C. Compile error
D. 0
Q8 – determine the output of the program
#include<stdio.h>
main()
{
unsigned q = 5, n=&q, *p = n+0;
printf("%u",*p);
}
A. Address of p
B. Address of n
C. Address of q
D. 5
Q9 – Consider the code below, determine the output of the program
#include<stdio.h>
main()
{
int p = 8;
if(q==8)
{
if(p==8) break;
printf("You are Right");
}
printf("Hello");
}
A. You are Right
B. You are RightHello
C. Hello
D. Compile error
Q10 – Consider the code, determine the program output
#include<stdio.h>
main()
{
int a = 8;
if(a=8)
{
if(a=8) printf("You Are Right");
}
printf("Hello”);
}
A. Compile error
B. You Are RightHello
C. Hello
D. You Are Right
Q11 – Consider the code snippet, determine the output of the program
#include<stdio.h>
main()
{
for(4;5;6)
printf("Welcome");
}
A. Compile error
B. No output
C. Prints “Welcome” once
D. Infinite loop
Q12 – Consider the code below, what will be the value of a?
int a = ~1;
A. 2
B. -1
C. 1
D. -2
Q 1 –from the statement below, which is true concerning the features of JavaScript?
A. JavaScript is integrated with Java
B. JavaScript is a lightweight, interpreted programming language
C. All of the above
Q 2 –identify the correct feature of JaveScript in the statement below?
A. JavaScript is corresponding to and embedded with HTML
B. Open and cross-platform
C. A and B are True
D. All of the above
Q 3 - Which of the statement below is true of the advantage of JavaScript?
A. Less server interaction
B. Increased interactivity
C. Immediate feedback to the visitors
D. All of the above
Q 4 - Which of the statement below is true about variable naming conventions in JavaScript?
B - Variable names are case sensitive.
A - JavaScript variable names must begin with underscore or letter.
C – A and B is True
D - None of the above
Q 5 – Is it possible to access Cookie using JavaScript?
A. True
B. False
Q 6 - Which statement below is true regarding cookie handling in JavaScript?
A. JavaScript can modify, create, read, and delete the cookie (s) of a webpage
B. JavaScript can control cookies via the property of the cookie.
C. A and B is True
D. None of the above
Q 7 – Identify the correct syntax to redirect a url using JavaScript?
A. browser.location='http://www.newlocation.com';
B. document.location='http://www.newlocation.com';
C. navigator.location='http://www.newlocation.com';
D. window.location='http://www.newlocation.com';
Q 8 – Choose the right syntax to print a page using JavaScript
A. browser.print();
B. document.print();
C. navigator.print();
D. window.print();
Q 9 – Identify the valid type of function supported by JavaScript?
A. anonymous function
B. Both of the above
C. named function
D. None of the above
Summary of the Book
Congratulations on purchasing Python for beginners, and thank you for doing
so.
The following chapters will discuss python programming language in detail
with a lot of examples and hands-on exercises. We will also look at a lot of
basic concepts in a way that beginners can understand and appreciate the
robustness of Python when compared to other entry-level programming
languages.
We will first start with a brief introduction that is followed by the installation
of Python development environments in the native system. We will then
introduce basic programming concepts like variables, operators, conditional
and loop structures with a lot of examples to make the reader understand
Python language in detail.
A lot of programming code is also given so that the reader can get a good
idea on both theoretical and programmatical concepts. Let us start
our journey into the world of Python.
There are plenty of books on this subject on the market, so thanks again for
choosing this one! Every effort was made to ensure it is full of as much
useful information as possible. Please enjoy!
Chapter 1: Introduction to Python
This chapter introduces a brief knowledge to Python along with its history.
This is quite basic and may involve theoretical background to make things
easy for the beginners. We will also introduce an example program so that we
can get a good starting feel for Python environment. Let us start for our very
first chapter in this book.
What is Python?
Python is a dynamic explanatory programming language. Python is easy to
learn and powerful and supports object-oriented and functional programming.
Python can be used on multiple operating systems such as Windows and
UNIX, while Python can be used on development platforms such as Java and.
NET, so it is also called "beginners programming language." Python's
simplicity and ease of use make the development process concise, especially
suitable for rapid application development.
In the next section, we will discuss a few basic historical advancements that
lead to the discovery of the Python programming language.
1. Object-oriented features
Object-oriented programming solves the complexity of structured
programming and makes programming closer to real life. Structured
programming mixes data and logic together, which is not convenient for
program maintenance. Object-oriented programming abstracts the behaviors
and attributes of objects and separates the behaviors and attributes but
organizes them together reasonably.
Python language has strong object-oriented characteristics and simplifies the
implementation of object-oriented. It eliminates object-oriented elements
such as protection types, abstract classes, interfaces, etc., making the concept
of object-oriented easier to understand.
2. Built-in data structure
Python provides some built-in data structures that implement functions
similar to collection classes in Java. Python's data structure includes tuples,
lists, dictionaries, collections, etc. The appearance of the built-in data
structure simplifies the design of the program. Tuples are equivalent to "read-
only" arrays, lists can be used as variable-length arrays, and dictionaries are
equivalent to Hash Table types in Java.
3. Simplicity
Python has fewer keywords. It does not have semicolons, begin, end, etc. The
code blocks are separated by spaces or tab indents. Python's code is simple,
short, and easy to read. Python simplifies loop statements and can be read
quickly even if the program structure is very complex.
4. Robustness
Python provides an exception handling mechanism that can catch exceptions
in programs. In addition, Python's stack trace object can point out the location
of the program error and the cause of the error. Exception mechanism can
avoid unsafe exit and help programmers debug programs.
5. Cross-platform
Python is compiled into platform-related binary code before interpretation
and execution. This approach is similar to Java, but Python's execution speed
has increased. Python-written applications can run on different operating
systems such as Windows, UNIX, Linux, etc. Python code written on one
operating system can be ported to other operating systems with only a few
modifications.
6. Scalability
Python is a language developed by C, so it can be extended by C, and new
modules and classes can be added to Python. At the same time, Python can be
embedded into projects developed in C and C++ languages to make the
program have script language.
7. Dynamics
Python is similar to JavaScript, PHP, Perl, and other languages. It does not
need to declare another variable. It can create a new variable by directly
assigning a value.
8. Strongly Typed Languages
Python's variables are created to correspond to a type, which can determine
the type of variables according to the content of the assignment expression.
Python has built a mechanism to manage these variables internally. Different
types of variables require type conversion.
9. Wide usage
Python language is applied to the database, network, graphic image,
mathematical calculation, Web development, operating system expansion,
and other fields. Python is supported by many third-party libraries. For
example, the PIL library (now no longer maintained but replaced by Pillow)
is used for image processing, the NumPy library is used for mathematical
calculation, the WxPython library is used for GUI program design, and the
Django framework is used for Web application program opening.
With this explanation, we can easily understand the advantages of python
programming language offers. Next, we will give an example program that
will let us introduce to Python language.
Code is here:
if __name__ =="__main__":
print ( " This is a whole new world" )
Code Description:
The first line of code is equivalent to the main () function in C language and
is the entrance of Python program. The second line of code uses the print
statement to output the string "This is a whole new world."
Command is here:
python filepath samplefilename.py
Where samplefilename.py represents python's source code file, filepath
represents the path where samplefilename.py is located. Enter the command
shown in the DOS window and run the file sample.py.
This mode of operation is not intuitive enough and is not convenient for
program debugging. Later, we will explain how to run Python programs in
editors like Edit Plus and development tool PyCharm.
In the next section, we will describe the python development environment in
detail.
Use of PyCharm
PyCharm is a cross-platform IDE that is very easy to use. It is developed in
Java. It has a paid version and a community free version. This book will use
the community free version. You can install it after downloading. After the
installation is completed, running the program for the first time will require
setting a theme, etc. You can choose to skip this step or choose yourself.
After setting up, restart, you can enter the program. Because it is an IDE, you
first need to create a project, and then you will need to set up a Python path
step by step, according to the requirements.
Note: If Anaconda is used, you need to select python.exe in py3k under envs
directory. Otherwise, the default Python2.7 version 2.7 will be used.
PyCharm has its own Python command line interactive Terminal, which can
easily run code and do related tests. Move the mouse to the lower-left corner
and click the TERMINAL button to open it, which is very convenient.
Click the [File] | [New] menu and select the corresponding file type to create
a new file and write a Python program in it. Now start to create
hello_world.py file, select the Run command in the [Run] menu or press
Alt+Shift after writing +F10 key combination can run the code.
In addition, PyCharm also supports advanced functions such as quick jump,
code refactoring, code testing, version control, debugging, etc. Next, we will
talk about the Eclipse development environment.
The first line of code enables Python programs to run on UNIX platforms.
Note that in Edit Plus, you can view the list of functions in the current Python
file by using the shortcut Ctrl + F11. You need to save the Python program
before running it. Next, use Edit Plus to write a Python program and output
the result.
This chapter on a whole level will introduce a lot of basic concepts that
programming languages deal with. We will be discussing concepts like
variables and data types with programmatical examples in the coming
sections. Let us start diving into the world of variables in Python.
The most basic data processing objects in programming languages are
constants and variables. Their main purpose is to store data for various
calculations and processing in programs. In this chapter, we will discuss
Python's basic data processing functions such as data types, variables, and
constants, and introduce beginners to the basic syntax they need when writing
small applications.
For example:
> > firstsample = 3
>>>second sample= 5
> > > result = firstsample+secondsample
In the above program statement, firstsample, secondsample, result are
variables, and number 3 is the variable value of firstsample. Since the
capacity of memory is limited, in order to avoid wasting memory space, each
variable will allocate memory space of different sizes according to
requirements, so "Data Type" is used to regulate it.
Decimal Module
This is a Python standard module library. Before using it, you need to import
this module with import instruction before using it. After correctly importing
this module, we can use the decimal. Decimal class to store accurate
numbers. If the parameter is not an integer, we must pass in the parameter as
a string.
For example:
import decimal
Num = decimal.decimal ("0.1")+decimal.decimal ("0.2")
And the result will be 0.3. Use the round () function to force the specified
number of decimal places round(x[, n]) to be a built-in function, which
returns the value closest to parameter x, and n is used to specify the number
of decimal places returned.
For example:
result = 0.1+0.2
The program statement above print (round(num, 1)) takes the variable num to
one decimal place, thus obtaining a result of 0.3. 2.2.3 Boolean Data Type
(bool) is a data type that represents the logic and is a subclass of int, with
only True value (true) and False value (false). Boolean data types are
commonly used in program flow control. We can also use the value "1" or
"0" to represent true or false values.
For example, the string and integer cannot be directly added, and the string
must be converted to an integer. If all the operations are of numeric type,
Python will automatically perform type conversion without specifying the
forced conversion type.
For example:
num = 5+0.3
# Result num=5.3 (floating-point number)
Python will automatically convert an integer to floating-point number for
operation. In addition, Boolean values can also be calculated as numeric
values. True means 1, False means 0.
For example:
num = 5+True
# result num=6 (integer).
If you want to convert strings to Boolean values, you can convert them by
bool function. Use the print () function in the following sample program to
display Boolean values.
[sample procedure: bool.py]
converts bool type
print(bool(0))
print(bool("") )
print(bool(" ") )
print(bool(1) )
The execution results of the 05 print(bool("ABC ") sample program are
shown. Program Code Resolution: Line 02: An empty string was passed in,
so False was returned. Line 03 returns True because a string containing a
space is passed in. When using Boolean, it values False and True, pay special
attention to the capitalization of the first letter.
Constant
Constant refers to the value that the program cannot be changed during the
whole execution process. For example, integer constants: 45, -36, 10005, 0,
etc., or floating-point constants: 0.56, -0.003, 1.234E2, etc. Constants have
fixed data types and values.
The biggest difference between variable and constant is that the content of the
variable changes with the execution of the program, while the constant is
fixed. Python's constant refers to the literal constant, which is the literal
meaning of the constant. For example, 12 represents the integer 12. The
literal constant is the value written directly into the Python program.
If literal constants are distinguished by data type, there will be different
classifications, for example, 1234, 65, 963, and 0 are integer literal constants.
The decimal value is the literal constant of the floating-point types, such as
3.14, 0.8467, and 744.084. As for the characters enclosed by single quotation
marks (') or double quotation marks ("), they are all string literal constants.
For example," Hello World "and" 0932545212 "are all string literal constants.
print("{0:<8}{1:^5}{2:^5}{3:^5}{4:^5}{5:^5}{6:^5}{7:^5}.” \
format("name,”"working1,”"working2,”"working3,” \
"working4,”"working5,”"working6,” \
"working7"))
print("{0:<8}{1:^5}{2:^5}{3:^5}{4:^5}{5:^5}{6:^5}{7:^5}.” \
format(name,working1,working2,working3,working4,working5,working6,working7))
ave=total/7
print("total cost: {0:<8} average daily cost {1: 5}.” format (total, ave))
With this, we have completed a brief explanation regarding python and its
basic concepts that are necessary for understanding traditional programming
methodology. In the next chapter, we will discuss in detail about Operators
and other moderate level topics that are necessary for a clear understanding of
programming.
Chapter 3: Operators in Python
In this chapter, we will explain about operators in detail. Operators are very
necessary for programming knowledge. We will look at about them in detail
in the next sections that follow.
Arithmetic operator
This is the most frequently used operator in programming languages. It is
commonly used for some four operations, such as addition operator,
subtraction operator, multiplication operator, division operator, remainder
operator, division operator, exponent operator, etc. The +, -, *, and/operators
are the same as our common mathematical operation methods, while the sign
operator is mainly used to represent the positive/negative value of operands.
Usually, the + sign can be omitted when the constant is set to a positive
number.
For example, "first=5" and "first=+5" have the same meaning. In particular,
we should remind everyone that negative numbers are also represented by the
"-" operator. When negative numbers participate in subtraction, in order to
avoid confusion with subtraction operators, it is better to separate negative
numbers with small brackets "().”
"/"and "//"are both division operators. The operation result of "/"is a floating-
point number. The "//"will remove the decimal part of the division calculation
result and only takes the integer. The "%" operator is the remainder.
For example:
first= 5
second= 2
Print(first/second) # result is floating-point number 2.5
Print(first// second) # result is integer 2
Print(first% second) # Result Is Remainder 1
If the result of the operation is not assigned to other variables, the data type
of the operation result will be dominated by the variable whose data type
occupies the largest memory space in the operand. In addition, when the
operands are integers, and the operation result will produce decimals, Python
will automatically output the result as decimals. We do not need to worry
about the conversion of data types.
However, if the operation result is to be assigned to a variable, the memory
space occupied by the variable must be large enough to prevent the
excessively long part of the operation result data from being discarded. For
example, if the result of the operation is a floating-point number and is
assigned to an integer variable, the decimal part of the operation result will be
truncated.
The division "/"operator in the arithmetic operator is a conventional division.
The quotient obtained after the operation is a floating-point number. If the
quotient is expressed as an integer, the int () function can be called.
Int(15/7) # Output 2 "* *" is a power operation, for example, to calculate the
fourth power of 2:
print(7** 4) # The result is 28
Note that the priority of arithmetic operators +, -, *, and/is "multiply and
divide first, then add and subtract." The following example illustrates that the
operation result of the above formula of 10+2*3 is 16. In the expression, the
precedence of parentheses is higher than in multiplication and division.
If the above expression is changed to (10+2)*3, the operation result will be
36. If operators with the same priority are encountered, the operations are
performed from left to right. Let's take a look at the application of the simple
four operations with an example program.
This sample program allows users to input Celsius temperature and convert it
to Fahrenheit temperature through program operation.
The formula for converting Celsius temperature to Fahrenheit temperature is
F=(9/5)*C+32.
[sample procedure: sampletemp.py]
Celsius temperature is converted to Fahrenheit temperature
-*- coding: utf-8 -*-
#converts the input Celsius temperature into Fahrenheit temperature
Tip: F = (9/5) * C+32
Celsius = float( input ("Give the Celsius temperature"))
Fahren = (9 / 5) * Celsius + 32
The execution results of the 08 print ("Celsius temperature {0} is converted
to Fahrenheit temperature {1}.”format(C,F)) .
Program Code Resolution:
Line 02: Let the user input Celsius temperature and call float () function to
convert the input into a floating-point data type.
Line 03: Converts the input Celsius temperature to Fahrenheit.
Line 04: Output the conversion between Celsius and Fahrenheit according to
the specified format string. Incidentally, the "+" sign can be used to connect
two strings.
sample="mno"+"pqrs"
# result sample = "mnopqrs"
Assignment operator
The assignment operator "=" consists of at least two operands. Its function is
to assign the value to the right of "=" to the variable to the left of the equal
sign. Most beginners of many programming languages cannot understand the
meaning of the equal sign "=" in programming languages.
It is easy to confuse it with the mathematical equivalent function. In
programming languages, the "=" sign is mainly used for assignment, but we
understand it from a mathematical point of view, and "=" used to be
considered as the concept of "equal."
For example, the following program statement:
addition = 0;
addition= addition + 1;
The meaning of addition=0 in the above program statement is also easy to
understand, but for the statement addition=addition+1, many beginners often
cannot understand the meaning of this statement. In fact, the "=" in Python
programming language is mainly used for "assignment."
We can imagine that when a variable is declared, the memory will be
allocated, and the memory address will be arranged. Only when the specific
value is set to the variable by using the assignment operator "=" will the
memory space corresponding to the memory address be allowed to store the
specific value.
In other words, addition= addition+1 can be seen as the result of adding 1 to
the original data value stored in the sum memory address, and then re-
assigning to the memory space corresponding to the sum memory address.
The right side of the assignment operator "=" can be a constant, variable or
expression, and will eventually assign the value to the variable on the left.
On the left side of the operator can only be variables, not numeric values,
functions, expressions, etc. For example, the expression first-second=Third is
an illegal program statement.
Python assignment operators have two types of assignment: single
assignment and compound assignment.
1. Single assignment assigns the value on the right side of the assignment
operator "=" to the variable on the left.
For example, the sample1 = 10 assignment operator can assign the same
value to multiple variables at the same time, in addition to assigning one
value to the variable at a time. If we want multiple variables to have the same
variable value at the same time, we can assign variable values together. For
example, if you want variables first, second, and third to have values of 100,
the assignment statement can be written as follows:
first= second = third = 100 when you want to assign values to multiple
variables in the same line of program statements, you can separate variables
with ,”.” For example, if you want the variable first to have a value of 10, the
variable second to have a value of 20, and the variable third to have a value
of 30, write the assignment statement as follows: first, second, third = 10, 20,
and 30 python also allows ";.”
To continuously write several different program statements to separate
different expressions.
For example, the following two lines of program code:
result= 10
Index = 12 ";"can be used. Write the above two lines on the same line.
Please look at the following demonstration:
result= 10;
Index = 12 # concatenates two program statements or expressions with
semicolons in one line
2. The compound assignment
The compound assignment operator is formed by combining the assignment
operator "=" with other operators. The prerequisite is that the source operand
on the right side of "=" must have the same operand as the one receiving the
assignment on the left side. If an expression contains multiple compound
assignment operators, the operation process must start from the right side and
proceed to the left side step by step,
For example:
first+= 1 # is equivalent to first = first+1
first-= 1 # is equivalent to first = first-1 with "A+=B;"
For example, a compound assignment statement is an assignment statement
"first=first+second;” The simplified writing of is to perform the calculation of
first+second first, and then assign the calculation result to the variable first.
In Python, first single equal sign "=" indicates assignment, and two
consecutive equal signs "= =" are the "equality" of relational comparison
operators and cannot be mixed. Note that when using the assignment
operator, if you want to assign one variable to another, the first variable must
first set the initial value; otherwise, an error will occur.
For example, result =result*10 because no initial value has been assigned to
num variable, if the assignment operator is directly used, an error will occur
because result variable has not been set to any initial value.
The following is a sample program for the comprehensive application of
assignment operators.
[example program: assigning.py]
# comprehensive application of assignment operator
01 # -*- coding: utf-8 -*-
02 """
03 Assignment application in python
04 """
05
06 black = 1
07 white = 2
08 red = 3
09
10 green = black+ white * red
11 print("{}.”format(black))
12 black += red
13 print("black={0}.”format (black, white)) #black=1+3=4
14 black -= white
15 print("black={0}.”format(black, white)) #black=4-2=2
16 black *= white
17 print("black={0}.”format(black,white)) #black=2*2=4
18 black **= white
19 print("black={0}.”format(black,white)) #black=4**2=16
20 black /= white
21 print("black={0}.”format(black,white)) #black=16/2=8
22 black //= white
23 print("black={0}.”format(black,white)) #black=8//2=4
24 black %= red
25 print("black={0}.”format(black,white)) #black=4%3=1
26 red = "Python"+"fun"
The execution result of the 27 print(s) program will appear.
Program code analysis:
Lines 12 and 13: assign the result of adding black and red to variable white,
and then output the result value of black.
Lines 14 and 15: assign the result of subtraction between black and white to
variable black, and then output the result value of black.
Lines 16 and 17: assign the result of multiplying black and white to variable
black, and then output the result value of black.
Lines 18 and 19: assign the result of black and white power to variable black,
and then output the result of black.
Lines 20 and 21: assign the result of dividing black and white to variable
black, and then output the result value of black.
Lines 22 and 23: assign the result of dividing black and white integers to
variable black, and then output the result value of black.
Lines 24 and 25: assign the remainder of black and white to variable black,
and then output the result of black.
Comparison operator
The comparison operator is also called a relational operator and is used to
determine whether the operands on the left and right sides of a conditional
expression are equal, greater than or less than. When using relational
operators, the results of the operations are either True or False, corresponding
to Boolean values of true or false.
If the expression is True, it will get "true"; otherwise, it will get "False." The
comparison operator can also be used in series, for example,
black<white<=red equals black<red, and white<=red. Note that two
consecutive equal signs "= =" are used to indicate the equality relationship,
while a single equal sign "=" indicates the assignment operator.
As has been repeatedly stressed above, this gap is easy to cause negligence in
writing program code. This is a very popular small "Bug" when debugging
programs in the future.
[example program: comparisionsample.py]
Comprehensive application of comparison operator
Logical operator
Logical Operator (LOGICAL OPERATOR) is used to judge basic logical
operations and can control the process of program operation. Logical
operators are often used in conjunction with relational operators, and the
results of operations are only True and False. Logical operators include and,
or, not, etc.
Beginners of programming use a truth table to observe logical operations
more clearly. Truth table lists all combinations of operands true (T) and false
(F) and the results of logical operations. As long as you understand the
working principles of AND, or, and not, plus the aid of truth table, you can be
familiar with logical operations quickly without memorizing it.
1. Logical and (And)
Logical AND must hold both left and right operands before the operation
result is true. When either side is False, the execution result is false. For
example, the logical result of the following instruction is true:
first= 10
second= 20
first < second and first ! = second #True Logical and Truth Table
2. Logical or (Or)
Logical OR As long as either of the left and right operands holds, the result
of the operation is true. For example, the following logical operation is true:
sample = 10
result = 20
sample< result or sample == result #True if the expression sample < result on
the left holds, the result of the operation is true, and there is no need to judge
the relation comparison expression on the right.
~ (not)
Not takes the complement of 1, i.e., all binary bits are inverted, i.e., 0 and 1
of all bits are exchanged. For example, first=12, the binary representation is
0000 1100, after the compliment is taken, since all bits of 0 and 1 will be
exchanged, the calculated result is -13.
The so-called "compliment" means that when two numbers add up to a
certain number (e.g., the decimal is 10), they are said to be complements of
the certain number. For example, the 10’s complement of 3 is 7, and the 10’s
complement of 7 is 3. For the binary system, there are two kinds of "1's
complement system" and "2's complement system." 1's complement system
"refers to the complement of two numbers that are 1 each other if the sum of
the two numbers is 1, i.e., the complement of 0 and 1 that are 1 each other.
In other words, in order to obtain the complement of the binary number, one
need only change 0 to 1 and 1 to 0. For example, (1111101001010)2 is
complemented by (10101010101)2. "2’s complement system" must calculate
the 1’s complement of the number in advance and add 1.
The following example program is an example of the application of bit
operators.
[example program: bitwiseapplication.py]
Comprehensive application of bit operators
01 # -*- coding: utf-8 -*-
02 """
Comprehensive Application of 03-bit Operator
04 """
05 first = 12; second = 38
06 bin(first); Bin(second) # Call the bin () function to convert first and
second into binary
07 print(first & second) # & operation result is 00000100, and then converted
to decimal value
08 print (first second) operation is 10101010, which is then converted into a
decimal value.
09 print(first | second) # | the result of the operation is 0101001010, which is
then converted into a decimal value.
10 print(~first) # ~ operation is the execution result of the complement
program taking
Program code analysis:
Line 07:
The binary representation of first=12 is first=00001100, the binary
representation of second=38 is second=00100110, and the result of the &bit
logic operation is 00000100, which is then converted into a decimal value of
4.
Line 08:
The binary representation of first=12 is first=00001100, the binary
representation of second=38 is first = first=00100110, the result of bit logic
operation is 00101010, and then the decimal value is 42.
Line 09:
The binary representation of first=12 is first =00001100, the binary
representation of second=38 is first = 00100100110, and the result of | bit
logic operation is 00101110, which is then converted to a decimal value of
46.
Line 10:
The binary representation of first=12 is first =00001100, and the result of its
complement of 2 is 11110011, which is then converted to a decimal value of
-13.
Operator Precedence
An expression often contains many operators. Operator precedence
determines the sequence of program execution, which has a significant
impact on the execution result and should not be taken lightly.
Tips
If CSV files and. py files are placed in different folders, the full path of the
files must be added. The open () command will open the csvfile and return
the file object. The sample program assigns the file object to the CSV file
variable. The default file uses unicode encoding.
If the file uses a different encoding, the encoding parameter must be used to
set the encoding. The CSV file used in this sample program is in an utf-8
format without BOM, so encoding="utf-8." The csv.reader () function reads
the CSV file, converts it into a reader object, and returns it to the caller. The
reader object is a string List object that can be an iterator.
In the above program, the reader variable is used to receive the reader object,
and then the data is read line by line through the
For loop: getit = csv.reader(csvfile)
# returns the reader object
For row in reader:
#for loop reads data row by row into row variable list object is Python's
Container Type.
Each element can be accessed by using the subscript (index, or index) of the
bracketed “[]” collocation element. The subscript starts from 0 and is row[0]
and ROW [1] from left to right, respectively. For example, to obtain the value
of the 4th element, it can be expressed as follows: name = row[3] trick to
open a file using with the statement before reading or writing the file, the file
must be opened using the open () function.
When reading or writing is complete, the file must be closed using the close
() function to ensure that the data has been correctly read or written to the
file. If an exception occurs before calling the close () method, then the close
() method will not be called.
For example:
f = open("results.csv") # to open the file
Csvfile = f.read() # read file contents
1 / 0 #error
F.close() # The program statement in line 3 of the close file made an error
with denominator 0.
Once executed, the program will stop executing, so close () will not be called,
which may risk file corruption or data loss. There are two special methods to
avoid this problem: one method is to add try … exception statements to catch
errors, and the other method is to use with statements.
Python's with statement is equipped with a special method. After the file is
opened, if the program is abnormal, the close () method will be automatically
called, so as to ensure that the opened file is closed correctly and safely.
The program code shows that the scores.csv file used in this sample program
contains the names of 10 students and their scores in mathematics, English,
and Chinese. We need to sum up the scores in the three subjects, calculate the
average score, and then use the average score to evaluate the grades.
The first line of the score CSV file is the title and must be skipped. Therefore,
we use a variable x to record the currently read line number. The initial value
of x is 0, and x must be greater than 0 before the if condition judgment
expression is true. The code is as follows:
With open ("results. CSV,” encoding = "utf-8") as CSV file:
first= 0 # sets the initial value of first to 0
For row in csv.reader(csvfile):
If first>0: # if first > 0, the if judgment expression is true
…
first+= 1 # is equivalent to indenting different blocks when writing Python
programs with first=first+1. The above statement has three blocks, namely
with…as block, for-loop block, and if block. The statement of first=0 must be
placed outside the for loop, and the statement of first+= 1 must be placed
inside the for loop, so that first will accumulate for each loop.
After entering the if block, the scores of the three subjects should be added
up. Since the csv.reader function reads in string format, it must be converted
into int format before calculation. Then assign the sum result to the variable
score.
The score intervals of the four grades are as follows. firstclass: 80 ~ 100
points on average. secondclass: 60 ~ 79 points on average. thirdclass: average
50 ~ 59 points. fourthclass: below 50 on average. An average of 80 to 100
points is rated as "first" and so on, and 80 points are also in this interval.
Therefore, the "> =" (greater than or equal to) relational operator must be
used. If only average>80 is used to judge, 80 points will not fall in this
interval.
The average score of 60 ~ 79 is rated as "second" and so on. This judgment
requires two conditions, average>=60 and average<80, and both conditions
must be met. Therefore, and must be used to judge: average > = 60 and
average < 80. Since these two conditions are a numerical interval, the
following expression can be written to indicate that the average value must be
within 60 ~ 79. 60 <= average < 80 full if...else statement is as follows:
If average >= 80:
Grade = "first"
elif 60 <= average < 80:
Grade = "second"
elif 50 <= average < 60:
Grade = "third"
Else:
Grade = "Fail"
At last, you only need to output the scoreTotal, average, and grade with a
print statement, and the execution result is displayed.
The following is the complete program code:
[sample procedure: Review_scores.py] transcript statistics assistant
01 # -*- coding: utf-8 -*-
02 """
03 Program Name: Report Card Assistant
04 Topic Requirements:
05 import CSV file
06 List the sum, average score and grade (first, second, third, fail)
07 first: average 80~100 points
08 second: average 60-79 points
09 third: average 50-59 points
10 fail: below 50 on average
11 """
12 import csv
14 print ("{0: < 3} {1: < 5} {2: < 4} {3: < 5} {4: < 5}.” format (",”"name,”
"total score,” "average score,” "grade"))
15 with open("results.csv,”encoding="utf-8") as csvfile:
16 first = 0
17 for row in csv.reader(csvfile):
19 if first > 0:
20 scoreTotal = int(row[1]) + int(row[2]) + int(row[3])
21 indent = circle(scoreTotal / 3, 1)
23 if indent >= 80:
24 grade = "first"
25 elif 60 <= indent< 80:
26 grade = "second"
27 elif 50 <= indent < 60:
28 grade = "third"
29 else:
30 grade = "fail"
32 print("{0:<3}{1:<5}{2:<5}{3:<6}{4:<5}.”format(first, row[0],
scoreTotal, average, grade))
34 result += 1
By this, we have completed a brief explanation about operators in detail.
Operators are important to master programming languages because they can
be used to create complex programs and software. The next chapter deals
with various advanced programming concepts like loops and conditionals.
We will discuss about these topics in detail. Why are you waiting? Let us
explore the next chapters.
Chapter 4: Conditional and Loops in
Python
This chapter describes moderate level topics like conditionals and loops in
detail. We will use different examples to explain these topics in detail. Let us
dive into knowing more about these concepts.
Condition 1: every 4 leaps (divisible by 4) and every 100 leaps (not divisible
by 100).
Condition 2: every 400 leaps (divisible by 400). One of the two conditions is
a leap year. Readers are asked to inquire whether the following years are leap
years: 1900 (flat year), 1996 (leap year), 2004 (leap year), 2017 (flat year),
2400 (leap year).
Multiple Choices
If there is more than one conditional judgment expression, elif conditional
statement can be added. Elif is like the abbreviation of "else if." Although
using multiple if conditional statements can solve the problem of executing
different program blocks under various conditions, it is still not simple
enough. Then, elif conditional statement can be used, and the readability of
the program can be improved.
Note that if the statement is a logical "necessity" in our program. Elif and else
do not necessarily follow, so there are three situations: if, if/else, if/elif/else.
The format is as follows:
If condition judgment
Expression 1:
# If the conditional judgment expression 1 holds, the program statement in
this program block is executed
Elif condition judgment
Expression 2:
# If the conditional judgment expression 2 holds, execute the program
statement in this program block
Else :
# If none of the above conditions hold, execute the program statement in this
program block,
For example:
If first==second:
# If first equals second, execute the program statement in this program block
Elif first>b :
# If first is greater than second, execute the program statement in this
program block
Else :
# if first is not equal to second and first is less than second, execute the
program statement in this program block. The following example program is
used to practice the use of IF multiple selection. The purpose of the sample
program is to detect the current time to decide which greeting to use.
[sample procedure: currentTime.py]
Detects the current time to decide which greeting
01 # -*- coding: utf-8 -*-
02 """
03 Program Name: Detect the current time to decide which greeting to use
04 Topic Requirements:
05 Judging from the current time (24-hour system)
06 5~10:59, output "good morning"
07 11~17:59, output "good afternoon"
08 18~4:59, output "good night"
09 """
11 import time
13 print ("current time: {}.” format (time.strftime ("%h:% m:% s"))
14 h = int( time.strftime("%H") )
16 if h>5 and h < 11:
17 print ("good morning!" )
18 elif h >= 11 and h<18:
19 print ("good afternoon!" )
20 else:
21 print ("good night!")
The execution results of the program will be shown on the screen.
The output shows the current time in the sample program to judge whether it
is morning, afternoon, or evening, and then displays the appropriate greeting.
Python's time module provides various functions related to time. The Time
module is a module in Python's standard module library.
Before using it, you need to use the import instruction to import and then call
the strftime function to format the time into the format we want. For example,
the following program statement is used to obtain the current time.
Import time
Time.strftime ("%h:% m:% s")
# 18: 36: 16 (6:36:16 p.m. 24-hour)
Time. strftime ("%i:% m:% s")
# 06:36:16 (6: 36: 16 p.m. 12-hour system) format parameters to be set are
enclosed in parentheses.
Pay attention to the case of format symbols. The following program
statement is used to display the week, month, day, hour, minute, and second.
Print (time.strftime ("%a,% b% d% h:% m:% s")) execution results are as
follows: Monday, sep17 15: 49: 29 4.2.3 nested if sometimes there is another
layer of if conditional statement in the if conditional statement. This multi-
layer selection structure is called nested if conditional statement.
Usually, when demonstrating the use of nested if conditional statements, it is
more common to demonstrate multiple choices with numerical ranges or
scores. In other words, different grades of certificates will be issued for
different grades of achievements.
If it is more than 60 points, the first certificate of competency will be given, if
it is more than 70 points, the second certificate of competency will be given,
if it is more than 80 points, the third certificate of competency will be given,
if it is more than 90 points, the fourth certificate of competency will be given,
if it is more than 100 points, the all-round professional certificate of
competency will be given.
Based on nested if statements, we can write the following program:
Available= int(input ("Give a score:")
If available >= 60:
Print ('First Certificate of Conformity')
If available >= 70:
Print ('Second Certificate of Conformity')
If available >= 80:
Print ('Third Certificate of Conformity')
If available >= 90:
Print ('Fourth Certificate of Conformity')
If getScore == 100:
Print ('All-round Professional Qualification Certificate') is actually an if
statement that is explored layer by layer. We can use the if/elif statement to
filter the multiple choices one by one according to conditional expression
operation and select the matching condition (True) to execute the program
statement in a program block.
The syntax is as follows:
If Conditional Expression 1:
The program block to be executed in accordance with conditional expression
1
Elif conditional expression 2:
The program block to be executed in accordance with conditional expression
2
Elif conditional expression n:
The program block to be executed according to the conditional expression n
Else:
If all the conditional expressions do not conform, this program block is
executed. When the conditional expression 1 does not conform, the program
block searches down to the finally conforming conditional expression.
The elif instruction is an abbreviation of else if. Elif statement can generate
multiple statements according to the operation of a conditional expression,
and its conditional expression must be followed by a colon, which indicates
that the following program blocks meet this conditional expression and need
to be indented.
The following example program is a typical example of the combined use of
nested if and if/elif statements. This program uses if to determine which
grade the query results belong to. In addition, another judgment has been
added to the sample program. If the score integer value entered is not
between 0 and 100, a prompt message of "input error, the number entered
must be between 0 and 100" will be output.
Comprehensive use of nested if statements example:
01 # -*- coding: utf-8 -*-
02 """
03 Examples of Comprehensive Use of Nested if Statements
04 """
05 result = int(input (‘Give final grade:')
06
07 # First Level if/else Statement: Judge whether the result entered is
between 0 and 100
08 if result >= 0 and result <= 100:
09 # 2nd level if/elif/else statement
10 if result <60:
11 print('{0} below cannot obtain certificate of competency'. format(result))
12 elif result >= 60 and result <70:
13 print('{0} result is d'. format(result))
14 elif result >= 70 and result <80:
15 print('{0} result is c'. format(result))
16 elif result >= 80 and result <90:
17 print('{0} result is level b'. format(result))
18 else:
19 print('{0} result is grade a'. format(result))
20 else:
The execution results of the
21 print ('input error, input number must be between 0-100')
Program code analysis:
Lines 7-21: first-level if/else statement, used to judge whether the input result
is between 0 and 100.
Lines 10-19: the second-level if/elif/else statement, which is used to judge
which grade the inquired result belongs to.
In the next section, we will discuss loops one of the most important concepts.
While loop
If the number of loops to be executed is determined, then using the for loop
statement is the best choice. However, the while loop is more suitable for
certain cycles that cannot be determined. The while loop statement is similar
to the for loop statement and belongs to the pre-test loop. The working mode
of the pre-test loop is that the loop condition judgment expression must be
checked at the beginning of the loop program block.
When the judgment expression result is true, the program statements in the
loop block will be executed. We usually call the program statements in the
loop block the loop body. While loop also uses a conditional expression to
judge whether it is true or false to control the loop flow. When the
conditional expression is true, the program statement in the loop will be
executed. When the conditional expression is false, the program flow will
jump out of the loop.
The format of the While loop statement is as follows:
While conditional expression:
# If the conditional expression holds, the flow chart of executing the while
loop statement in this program block.
The while loop must include the initial value of the control variable and the
expression for increasing or decreasing. When writing the loop program, it
must check whether the condition for leaving the loop exists. If the condition
does not exist, the loop body will be continuously executed without stopping,
resulting in "infinite loop," also called "dead loop."
The loop structure usually requires three conditions:
(1) The initial value of the loop variable.
(2) Cyclic conditional expression.
(3) Adjust the increase or decrease the value of cyclic variables.
For example, the following procedure:
first=1
While first < 10: # Loop Condition Expression
print( first)
first += 1 # adjusts the increase or decrease value of the loop variable.
When first is less than 10, the program statement in the while loop will be
executed, and then first will be added with 1 until first is equal to 10. If the
result of the conditional expression is False, it will jump out of the loop.
For loop
For loop, also known as count loop, is a loop form commonly used in
programming. It can repeatedly execute a fixed number of loops. If the
number of loop executions required is known to be fixed when designing the
program, then the for-loop statement is the best choice. The for loop in
Python language can be used to traverse elements or table items of any
sequence. The sequence can be tuples, lists or strings, which are executed in
sequence.
The syntax is as follows:
For element variable in sequence:
# Executed instructions
Else:
The program block of #else can be added or not added, that is, when using
the for loop, the else statement can be added or not added. The meaning
represented by the above Python syntax is that the for loop traverses all
elements in a sequence, such as a string or a list, in the order of the elements
in the current sequence (item, or table item).
For example, the following x variable values can all be used as traversal
sequence elements of a
For loop:
first= "abcdefghijklmnopqrstuvwxyz "
second= ['january', 'march', 'may', 'july', 'august',
'october', 'december']
result= [a, e, 3, 4, 5, j, 7, 8, 9, 10]
In addition, if you want to calculate the number of times a loop is executed,
you must set the initial value of the loop, the ending condition, and the
increase or decrease value of the loop variable for each loop executed in the
for-loop control statement. For loop every round, if the increase or decrease
value is not specifically specified, it will automatically accumulate 1 until the
condition is met.
For example, the following statement is a tuple (11 ~ 15) and uses the for
loop to print out the numeric elements in the tuple: x = [11, 12, 13, 14, 15]
For first in x:
A more efficient way to write tuples is to call the range () function directly.
The format of the range () function is as follows: range([initial value], final
value [,increase or decrease value]) tuples start from "initial value" to the
previous number of "final value.” If no initial value is specified, the default
value is 0; if no increase or decrease value is specified, the default increment
is 1.
An example of calling the range () function is as follows: range (3) means
that starting from the subscript value of 0, 3 elements are output, i.e., 0, 1 and
2 are three elements in total.
Range(1,6) means starting from subscript value 1 and ending before subscript
value 6-1, that is, subscript number 6 is not included, i.e., 1, 2, 3, 4 and 5 are
five elements. ·range (4,10,2) means starting from subscript value 4 and
ending before subscript number 10, that is, subscript number 10 is excluded,
and the increment value is 2, i.e., 4, 6 and 8 are three elements. The following
program code demonstrates the use of the range () function in a for loop to
output even numbers between 2 and 11 for i in range (2, 11, 2).
One more thing to pay special attention to when using the for loop is the print
() function. If the print () is indented, it means that the operation to be
executed in the for loop will be output according to the number of times the
loop is executed. If there is no indentation, it means it is not in the for loop,
and only the final result will be output.
We know that calling the range () function with the for loop can not only
carry out accumulation operations but also carry out more varied
accumulation operations with the parameters of the range () function. For
example, add up all multiples of 5 within a certain range. The following
sample program will demonstrate how to use the for loop to accumulate
multiples of 5 within a range of numbers.
[Example Procedure: addition.py]
Accumulate multiples of 5 in a certain numerical range
01 # -*- coding: utf-8 -*-
02 """
03 Accumulate multiples of 5 within a certain numerical range
04 """
05 addition = 0 # stores the accumulated result
06
07 # enters for/in loop
08 for count in range(0, 21, 5):
09 addition += count # adds up the values
11 print('5 times cumulative result =',addition)
# Output cumulative result
Program code analysis:
Lines 08 and 09: Add up the numbers 5, 10, 15 and 20. In addition, when
executing a for loop, if you want to know the subscript value of an element,
you can call Python's built-in enumerate function. The syntax format of the
call is as follows: for subscript value, element variable in enumerate
(sequence element).
For example (refer to sample program enumerate. py):
names = ["ram,” "raju,” "ravi"]
for index, x in enumerate(names):
The execution result of the above statement in print ("{0}-{1}.” format
(index, x)) is displayed.
Nested loop
Next, we will introduce a for nested loop, that is, multiple for loop structures.
In the nested for loop structure, the execution process must wait for the inner
loop to complete before continuing to execute the outer loop layer by layer.
The double nested for loop structure format is as follows:
For example, a table can be easily completed using a double nested for loop.
Let's take a look at how to use the double nested for loop to make the nine
tables through the following sample program.
[Example Procedure: 99Table.py]
99 Table
01 # -*- coding: utf-8 -*-
02 """
03 Program Name: Table
04 """
05
06 for x in range(6,68 ):
07 for y in range(1, 9):
08 print("{0}*{1}={52: ^2}.”format(y, x, x * y), end=" ")
99 is a very classic example of nested loops. If readers have learned other
programming languages, I believe they will be amazed at the brevity of
Python. From this example program, we can clearly understand how nested
loops work. Hereinafter, the outer layer for the loop is referred to as the x
loop, and the inner layer for loop is referred to as the y loop.
When entering the x loop, x=1. When the y loop is executed from 1 to 9, it
will return to the x loop to continue execution. The print statement in the y
loop will not wrap. The print () statement in the outer x loop will not wrap
until the y loop is executed and leaves the y loop. After the execution is
completed, the first row of nine tables will be obtained. When all X cycles are
completed, the table is completed.
Note that the common mistake for beginners is that the sentences of the inner
and outer loops are staggered. In the structure of multiple nested loops, the
inner and outer loops cannot be staggered; otherwise, errors will be caused.
The continue instruction and break instruction are the two loop statements we
introduced before. Under normal circumstances, the while loop is to judge the
condition of the loop before entering the loop body. If the condition is not
satisfied, it will leave the loop, while for loop ends the execution of the loop
after all the specified elements are fetched. However, the loop can also be
interrupted by continue or break. The main purpose of break instruction is to
jump out of the current loop body, just like its English meaning, break means
"interrupt."
If you want to leave the current loop body under the specified conditions in
the loop body, you need to use the break instruction, whose function is to
jump off the current for or while loop body and give the control of program
execution to the next line of program statements outside the loop body. In
other words, the break instruction is used to interrupt the execution of the
current loop and jump directly out of the current loop.
Break
If a nested loop is encountered, the break instruction will only jump off the
loop body of its own layer, and will be used together with the if statement,
For example:
For first in range (1, 10):
If first == 5:
Break
Print( first, end= "")
When first is equal to 5, the break statement will be executed to leave the for
loop body, that is, the for loop will not continue to execute.
If we hope that a certain loop program can be executed continuously, and we
will not leave the loop until a certain condition is met, we can use the break
instruction at this time. If we want to design a game of guessing numbers, we
require the user to enter a number between 1 and 100.
If the input is wrong, we will inform the user that the input number is too
large or too small, and let the user repeat the input until the input number is
exactly the same as the original default answer.
At this time, we can use the break command to jump off the loop and output
the correct answer or the information such as the end of the game.
Look at the following program code:
number=9
while True:
Guess = int(input ('enter a number between 1 and 100->'))
if guess == number:
Print ('you guessed it, the number is:', number)
Break
Continue instruction
The function of the continue instruction is to force loop statements such as
for or while to end the program currently executing in the loop and transfer
control of program execution to the beginning of the next loop. In other
words, if the continue instruction is encountered during the execution of the
loop, the current round of loop will be immediately interrupted, all the
program statements that have not yet been executed in the subsequent round
of loop will be abandoned, and the program flow will be returned to the
beginning of the while or for loop to start the next round of loop.
In contrast, the break instruction will end and jump off the current loop body,
while the continue instruction will only end the current loop and will not
jump off the current loop,
For example:
for first in range(1, 10):
if first == 5:
continue
When first is equal to 5, the continue instruction is executed, and the program
will not continue to execute, so 5 is not printed by the print statement, and the
for loop will continue to execute.
Practical Exercises
This section will use a sample program to review the above-mentioned
related contents and make a simple password verification program. Example
program shows that writing a Python program can allow users to enter
passwords and perform simple password verification, but the number of
entries is limited to three and login is not allowed if the current password is
5656.
1. Input Description
When entering for the first time, we can deliberately enter the wrong
password, and the program will output "Wrong password!” and ask the user
to enter the password again. We can try to enter the wrong password again,
and we will also output "Wrong password!” If you enter the wrong password
more than three times in a row, you will no longer be allowed to continue
entering the password to log in, and you will be asked to enter "password
error for three times, cancel login!" If the password entered in the input
process is correct, the "correct password" will be output and ends the
execution of the program.
Program Code Description
The complete program code is listed below. The default password for the
password is the number 5656, and the variable I is used to record the total
number of inputs. If the number of inputs exceeds three, it will jump out of
the loop.
[sample procedure: password.py]
simple password verification procedure
01 # -*- coding: utf-8 -*-
02 """
03 let users enter passwords,
04 and perform simple password verification
05 However, the number of entries is limited to three. If the number exceeds
three, login is not allowed.
06 If the current password is 5656.
07 """
08
09 password=5656 # uses the password variable to store passwords for
verification.
10 first=1
12 while first<=3: # the number of inputs is limited to three
13 new_pw=int(input ("Give password:"))
14 if new_pw ! = password: # if the password entered is different from the
password
15 print ("wrong password! ! ! " )
16 first=first+1
17 continue # Jumps Back to while Start
18 else:
19 print ("correct password! ! ! " )
20 break
21 if first>3:
22 print ("password error 3 times, cancel login! ! ! \n");
# Password Error Handling
With this, we have completed the moderate concepts like conditionals and
loops that are very pivotal for the development of programs. In the next
chapter, we will discuss modules and functions that are important for the
application and software development. Python supports both function-
oriented and object-oriented paradigms. We will discuss everything python
offers for advanced programmers in detail in the next chapters.
Chapter 5: Modules and Functions in
Python
This chapter will introduce the concepts of modules and functions in Python.
Structured programming can decompose complex problems into several
components and define and implement modules and functions for the
components. This chapter will discuss in detail the features of Python
modules and functions. Finally, Python's functional programming will be
introduced.
Module Creation
A module organizes a set of related functions or codes into a file. A file is a
module. Modules consist of code, functions, or classes. To create a file
named myModule.py, a module named myModule is defined. Define a
function func () and a class MyClass in the myModule module. A method
myFunc () is defined in the MyClass class.
01 # custom module
02 def func():
03 print ("MyModule.func()")
04
05 class example:
06 def examplefun(self):
07 print ("MyModule.example.examplefun()")
Then create a file called _ myModule.py in the directory where mymodule.py
resides. The functions and classes of the myModule module are called in this
file.
01 # Calls Classes and Functions of Custom Modules
02 import myexample # import module
03
04 myexample.func()
05 myClass=myexample.MyClass()
06 myClass.myFunc()
[Code Description]
Line 2
Code Import Module myexample.
Line 4
This calls the examples' function. You need to prefix myexample when
calling; otherwise, Python does not know the namespace where function() is
located.
Output results:
myexample.func()
Line 5
This code creates an instance of the class Myexample. You also need to call
the class with the prefix myexample.
Line 6
Module Import
Before using a module's function or class, you must first import the module.
The module import has been used many times before, and the module import
uses the import statement.
The format of the module import statement is as follows.
import nameofthemodule
This statement can be directly imported into a module. When calling a
function or class of a module, you need to prefix it with the module name in
the following format.
nameofthemodule.func()
If you do not want to use prefixes in your program, you can import them
using the from…import… statement. The format of the from…import… the
statement is as follows.
from nameofthemodule import nameofthefunction
This compares the difference between the import statement and the from ...
import ... statement. Importing all classes and functions under the module can
use import statements in the following format.
from nameofthemodule import *
In addition, the same module file supports multiple import statements. For
example, define a module named myexample. The module defines a global
variable count and a function (). Every time the function () is called, the value
of the variable count is incremented by 1.
01 number =1
02
03 def function ():
04 global number
05 number=number+1
06 return the number
Import myexample module several times to see the result of variable count.
01 import myexample
02 print("count =,” myexample.func())
03 myexample.count=10
04 print ("count =,” myexample.count)
05
06 import myexample
07 print ("count =,” myexample.func())
[Code Description]
Line 1
Code Import Module myexample.
The second line of code calls the function () in the module. At this time, the
value of the variable count is equal to 2.
Output result:
number=2.
The third line of code assigns a value to the variable count in the module
myexample, where the value of the variable count is equal to 10.
The fourth line of code gets the value of the variable count.
Output result:
number=10.
The code in line 6 is imported into module myexample again, and the initial
value of variable count is 10.
The seventh line of code calls function(), and the value of variable count is
increased by 1.
Output result:
number =11.
Import statements in Python are more flexible than those in Java. Python's
import statement can be placed anywhere in the program or even in
conditional statements.
Add the following statement after the above code segment:
01 # import placed in the conditional statement
02 if myexample.number> 1:
03 myexample.number=1
04 else:
05 import myexample
06 print ("count =,” myexample.number)
[Code Description]
The second line of code judges whether the value of myexample.number is
greater than 1.
Line 3 code, if the value of count is greater than 1, set the value of variable
count to 1. Since the value of the variable count in the preceding code
segment is 11, the value of the variable count is assigned to 1.
Line 5 code, if the value of count is less than or equal to 1, import statement.
The sixth line of code outputs the value of the variable count. Output Result:
count=1
Properties of Modules
Modules have some built-in attributes that are used to complete specific
tasks, such as __name__, __doc__. Each module has a name; for example,
__name__ is used to determine whether the current module is the entry of the
program. If the current program is in use, __name__ has a value of
"__main__.” Usually, a conditional statement is added to each module to test
the function of the module separately.
For example, create a module myexample.
01 if __name__ =='__main__':
02 print ('myexample runs as main program')
03 else:
04 print ('myexample Called by Another Module')
[Code Description]
The first line of code determines whether this module is running as the main
program. Run the module myexample separately, and the output results are as
follows. Myexample runs as the main program.
Create another module myexample. This module is very simple, just import
module myexample.
01 import myexample
02 print (__doc__)
[Code Description]
Run the module myexample and output the result:
Myexample is called by another module. The second line of code calls
another module attribute __doc__. Since the module does not define a
document string, the output result is None.
Output Result:
None
Built-in Functions of Modules
Python provides an inline module build-in. The inline module defines some
functions that are often used in development. These functions can be used to
realize data type conversion, data calculation, sequence processing, and other
functions.
The functions commonly used in inline modules will be described below.
1. apply()
The apply function has been removed from Python3, so it is no longer
available. The function of calling the variable parameter list can only be
realized by adding * before the list.
2. filter()
Filter () can filter a sequence to determine whether the result returned by the
parameters of the custom function is true or not
Filter and return the processing results at one time.
The declaration of filter () is as follows.
class filter(object)
filter(function or None, iterable) --> filter object
The following code demonstrates the function of the filter () filter sequence.
Filters out numbers greater than 0 from a given list.
01 def func(x):
02 if first> 0:
03 return first
04
05 print (filter (function, range (-39,10))) # calls the filter function and
returns the filter object
06 print (list (filter (function, range (-94,10))) # converts filter object to list
[Code Description]
In line 5, use range () to generate the list to be processed, and then transfer
the values of the list to func (). Func returns the result to filter () and finally
returns the resulting yield as an iterable object, which can be traversed.
The output is as follows:
<filter object at 0x1022b2750>
Note that the parameter of the filter function func () in filter () cannot be
empty. Otherwise, there is no variable that can store the sequence element,
and func () cannot handle filtering.
3. reduce()
Continuous operations on elements in a sequence can be handled through
loops. For example, to accumulate elements in a sequence. Python's reduce ()
can also implement continuous processing. In Python2, reduce () exists in
global space and can be called directly. In Python3, it is moved to the
functools module, so it needs to be introduced before use. The declaration of
reduce () is as follows.
reduce(function, sequence[, initial]) -> result
[Code Description]
Parameter function is a self-defined function, which implements continuous
operation of the parameter sequence in function function().Parameter initial
can be omitted. If the initial is not empty, the value of initial will be passed
into function() for calculation first. If the sequence is empty, the value of
initial is processed.
The return value of reduce () is the calculated result of func ().
The following code implements the accumulation of numbers in a list.
01 def addition(first, second):
02 return first+second
03 form functools import reduce
# Introduce reduce
04 print (reduce(addition, range(0, 10)))
05 print (reduce(addition, range(0, 10), 10))
06 print (reduce(addition, range(0, 0), 10))
[Code Description]
The first line of code defines an addition () function, which provides two
parameters and performs an accumulation operation.
Line 4 code, perform accumulation calculation on 0+1+2+3+4+5+6+7+8+9.
The output is 45.
Line 5 code, perform accumulation calculation on
10+0+1+2+3+4+5+6+7+8+9. The output is 55.
In line 6, because range(0, 0) returns an empty list, the return result is 10.
The output is 10.
Reduce () can also perform complex cumulative calculations such as
multiplication and factorial on numbers. Note that if you use reduce () for
cumulative calculation, two parameters must be defined in sum to correspond
to the operands on both sides of the addition operator.
4. map()
Map () is used to "unpack" tuple, and the first parameter of map () is set to
None when calling. Map () is very powerful and can perform the same
operation on each element of multiple sequences and return a map object.
The declaration of map () is as follows.
class map(object)
map(func, *iterables) --> map object
[Code Description]
The parameter function is a custom function that implements the operation on
each element of the sequence. The parameter iterables is a sequence to be
processed, and the number of parameters iterables can be multiple.
The return value of map () is the processed list of sequence elements.
The following code implements the exponentiation of the numbers in the list.
01 def power(first): return first ** first
02 print (map (power, range (1,5))) # print map object
03 print (list (map (power, range (1,5))) # converted to list output
04 def power2(first, second): return first ** second
05 print (map (power2, range (1,5), range (5,1,-1))) # print map object
06 print (list (map (power2, range (1,5), range (5,1,-1))) # converted to list
output
[Code Description]
The first line of code defines a power () function, which implements the
power operation of numbers.
The second line of code passes the numbers 1, 2, 3 and 4 into the function
power, in turn, converts the calculation result yield into an iterable object,
and outputs the result:
map object at 0x7675678>
The third line of code converts the map object into a list and prints it out, and
outputs the result:
[1, 4, 27, 256]
The fourth line of code defines a power2 () function to calculate the Y power
of X.
The fifth line of code provides two list parameters. 1 5, 2 4, 3 3 and 4 2 are
calculated in turn, and the calculated results yield into an iterable object.
Output results:
<map object at 0x19876543234560>
Line 6 converts the map object into a list output.
Output results:
[21, 16, 29, 26]
Note that if multiple sequences are provided in map (), the elements in each
sequence are calculated one by one. If the length of each sequence is not the
same, then the short sequence is supplemented with None before calculation.
Custom Packages
A package is one that contains at least __init__.py files . Folders Python
package and Java package have the same function, both of which are to
realize the reuse of programs. They combine the code that realizes a common
function into a package and call the services provided by the package to
realize reuse. For example, define a package parent. Create two sub-packages
pack and pack2 in the parent package.
A module myModule is defined in the pack package, and a module
myModule2 is defined in the pack2 package. Finally, define a module main
in package parent and call sub-packages pack and pack2.
The __init__.py program for the package pack is as follows:
01 if __name__ =='__main__':
02 print ('run as first program')
03 else:
04 print ('pack initialization')
This code initializes the pack package and directly outputs a string. When the
pack package is called by other modules, "pack initialization" will be output.
The myexample module of the package pack is shown below.
01 def function():
02 print ("pack.myexample.func()")
03
04 if __name__ =='__main__':
05 print ('myexample runs as first program')
06 else:
07 print ('myexample Called by Another Module')
When pack2 is called by other modules, the __init__.py file will be executed
first. The __init__.py program for pack2 is as follows.
01 if __name__ =='__main__':
02 print ('run as first program')
03 else:
04 print ('pack2 initialization')
The myModule2 modules of pack2 are as follows.
01 def func2():
02 print ("pack2.myexample2.func()")
03
04 if __name__ =='__main__':
05 print ('myexample2 runs as main program')
06 else:
07 print ('myexample2 called by another module')
The main module below calls the functions in pack and pack2 packages.
01 from pack import myexample
02 from pack2 import myexample2
03
04 myexample.func()
05 myexample2.func2()
[Code Description]
The first line of code imports the myexample module from the pack package.
The myexample module is called by the main module, so the output string
"myexample is called by another module."
The output is as follows:
Pack initialization
Myexample is called by another module. The second line of code imports the
myexample2 module from the pack2 package.
The output is as follows:
Pack2 initialization
Myexample2 is called by another module. The fourth line of code calls
function() of myexample module.
The output is as follows:
pack.myexample.func()
Line 5 calls func2 () of myexample2 module.
The output is as follows:
pack2.myexample2.function()
__init__.py can also be used to provide a list of modules for the current
package. For example, add a line of code before the __init__.py file of the
pack.
__all__=["myexample"]
__all__ is used to record the modules contained in the current pack. The
contents in square brackets are the list of module names. If the number of
modules exceeds 2, separate them with commas. Similarly, a similar line of
code was added to the pack2 package.
__all__=["myexample2"]
In this way, all modules in pack and pack2 can be imported in the main
module at one time.
The modified main module is as follows:
01 from pack import *
02 from pack2 import *
03 myexample.func()
05 myexample2.func2()
[Code Description]
Line 1 code, first execute the __init__.py file of the pack and then look for
the modules contained in the pack in the __all__ attribute. If the __init__.py
file of the pack does not use the __all__ attribute to record the module name,
the main module will not recognize the myexample module when it is called.
Python will prompt the following error.
NameError: name 'myexample' is not defined.
Line 2 code has the same function as line 1 code.
Function
A function is a piece of code that can be called repeatedly and returns the
desired result by entering the parameter value. The previous example has
used Python's built-in functions many times and has also customized some
functions. Python's functions have many new features, which will be
described one by one below.
Definition of function
A function definition is very simple, using the keyword def definition.
Functions must be defined before use, and the type of function is the type of
return value. Python functions are defined in the following format.
01 def function name (parameter 1, parameter 2 ...):
02 …
03 return expression
The function name can be a string of letters, numbers, or underscores, but
cannot begin with a number. The parameters of the function are placed in a
pair of parentheses. The number of parameters can be one or more. The
parameters are separated by commas. Such parameters are called formal
parameters.
The parenthesis ends with a colon, and the body of the function follows the
colon. It uses a dictionary to implement a switch statement. Now wrap this
code into a function. It involves three parameters: two operands and an
operator.
The modified code is as follows.
01 # Function
02 from __future__ import division
03 def calculation (first, second, operator):
04 result={
05 "+":first+second,
06 "-":first-second,
07 "*":first * second,
08 "/":first / second
09 }
[Code Description]
The third line of code defines the function calculation(); the first and second
are the two operands of the four operations, and the operator is the operator.
The values of these three parameters are passed from the actual parameters.
Lines 4 to 9 are the main body of the function, realizing the operation of
operands.
Call of function
01 # Function
02 print (calculation(1, 2, "+"))
[Code Description]
calculation () is written after the print statement and directly outputs the
return value of the function. The output is "3.”
Note that the actual parameters must correspond to the formal parameters one
by one, otherwise erroneous calculations will occur — exceptions to
parameters with default values.
Parameters of function
In C and C++, there are two ways to pass parameters: value passing and
reference passing. Anything in Python is an object, so parameters only
support the way references are passed. Python binds the value of the actual
parameter to the name of the formal parameter through a name binding
mechanism. That is, the formal parameter is passed to the local namespace
where the function is located, and the formal parameter and the actual
parameter point to the same storage space in memory In between.
The parameters of the function support default values. When a parameter
does not pass an actual value, the function uses the default parameter
calculation. For example, you can provide a default value for all parameters
of calculation ().
Default Parameter for functions
01 # Function
02 def calculation(first=1, second=1, operator="+"):
03 result = {
04 "+" : first+second,
05 "-" : first-second,
06 "*" : first * second,
07 "/" : first / second
08 }
09 return result.get(operator)
# returns the calculation result
11 print (calculation(1, 2))
12 print (calculation(1, 2, "-"))
13 print (calculation(first=3, operator="-"))
14 print (calculation(second=4, operator="-"))
15 print (calculation(second=3, first=4, operator="-"))
[Code Description]
The code in line 2 defines the default value of the parameter by using an
assignment expression.
In line 11, the values of parameters x and y are assigned to 1 and 2
respectively, and the default value "+" is used for parameter operator. The
output is "3.”
Line 12 provides 3 actual parameters, which will override the default values
of formal parameters, respectively. The output result is "-1.”
Line 13 code, specify the values of parameters y and operator. The output
result is "-2.” The parameters must be passed in the form of assignment
expressions. Otherwise, the Python interpreter will mistakenly assume x=3,
y="- .” Therefore, the following wording is wrong.
print(calculation(3, "-"))
Line 14 code, specify the values of parameters x and operator. The output is
"3.”
Line 15 code, using assignment expression to pass parameters, can reverse
the order of the parameter list. The output is "1.”
Parameters can be variables or built-in data structures such as tuples and lists.
01 # list is passed as a parameter
02 def calculation(args=[], operator="+"):
03 first = args[0]
04 second = args[1]
05 result = {
06 "+" : first+second,
07 "-" : first-second,
08 "*" : first * second,
09 "/" : first/ second
10 }
12 print(calculation([1, 2]))
[Code Description]
The second line of code combines the parameters x and y into one parameter
and passes the values of x and y through the args list.
Lines 3 and 4 of code, take out parameter values from the list and assign
them to variables x and y respectively. Line 12 code, pass the list [1,2] to
calculation (). The output is "3.”
Because parameters implement the mechanism of name binding, unexpected
results may occur when using default parameters.
01 def join(args=[]):
02 args.join(0)
03 print (args)
04
05 join()
06 join([1])
07 join()
[Code Description]
The first line of code defines a join () function, and the argument is a default
list.
The second line of code joins an element 0 to the list.
Line 5 calls join (), using the default list. The output is' [0]'.
Line 6 code, passed a list [1], join () is joined with an element 0. The output
is "[1, 0].”
The seventh line of code calls join () again, and the list used at this time is
args called for the first time, so args will add another element 0 on the
original basis.
The output is' [0, 0]'.
To avoid this problem, a conditional judgment statement can be added to join
(). If there are no elements in the list args, empty the args list before adding
elements.
01 def join(args=[]):
02 if len(args) <=0:
03 args=[]
04 args.join(0)
05 print (args)
06
07 join()
08 join([1])
09 join()
[Code Description]
The second line of code uses len () to determine whether the length of the list
args is greater than 0. If less than or equal to 0, args is set to an empty list,
i.e., function parameters are unbound.
Line 4 adds an element 0 to the list.
Line 7 calls join (), using the default list. The output is' [0]'.
In line 8, a list [1] is passed, and an element 0 is joined to join (). The output
is "[1, 0].”
The 9th line of code calls join (), which cancels the name binding of the
parameter through the judgment of len(args). The output is' [0]'. In
development, it is often necessary to pass variable-length parameters.
This requirement can be met by using the identifier "*" before the parameter
of the function. "*" can refer to tuples and combine multiple parameters into
one tuple.
01 # Pass Variable Parameters
02 def function(*args):
03 print args
04 function(1, 2, 3)
[Code Description]
Line 2 code, use identifier "*" before argument args.
The code in line 3 outputs the value of the parameter. Because the parameter
uses the form of "*args,” the actual parameter passed in is "packed" into a
tuple, and the output result is "(1, 2, 3).”
The fourth line of code calls the function func (). The parameters "1,” "2" and
"3" become elements of args tuples.
Python also provides another identifier "* *.” Add "* *" before the formal
parameter to refer to a dictionary and generate the dictionary according to the
assignment expression of the actual parameter. For example, the following
code implements matching tuple elements in a dictionary.
When defining a function, two parameters are designed: one is the tuple to be
matched, which is denoted as "* t"; the other is a dictionary, which means
"*d.” When the function is called, the actual parameters are divided into two
parts: one part is several numbers or strings, and the other part is assignment
expression.
01 # Pass Variable Parameters
02 def find(*one, **two):
03 keys = one.keys()
04 values = two.values()
05 print(keys)
06 print (values)
07 for arg in t:
08 for key in keys:
09 if arg == key:
10 print ("find:,”d[key])
12 find("one,” "three,” one="1,”two="2,”three="3")
[Code Description]
"*t" in line 2 corresponds to "one" and "three" in line 12. "One" and "three"
form a tuple t. "**d" corresponds to "one="1,” two="2,” three="3",”
generating a dictionary {one: "1,”two:"2,”three: "3"}.
Line 5 code output results:
['three', 'two', 'one']
Line 6 code output results:
['3', '2', '1']
Lines 7 to 10 look up the value in tuple t in dictionary d. If found, output.
find: 1
find: 3
Note that "*" must be written before "* *,” which is a grammatical rule.
Reconstruction of function
01 # Multiple return Statements
02 def function(one):
03 if one> 0:
04 result="one> 0"
05 elif one ==0:
06 result="one ==0"
07 else:
08 result="one<0"
09 return result
11 print (func(-2))
[Code Description]
In lines 4, 6 and 8, a variable result is added to record the status of program
branches through assignment statements. The ninth line of code returns the
value of result, so that the result of each branch can be returned by calling the
same return statement.
Nesting of functions
Nesting of functions refers to calling other functions inside a function. C and
C++ only allow nesting within function bodies, while Python not only
supports nesting within function bodies but also supports nesting of function
definitions. For example, calculate the value of expression (one+two)*(first-
second). The calculation step can be divided into three steps: first, calculate
the expression one+two, then calculate the expression first-second, and
finally calculate the product of the results of the first two steps. Therefore, the
three functions can be designed. The first function sum () calculates the value
of one+two, the second function sub () calculates the value of m+n, and the
third function calculates the product of the first two.
The following code demonstrates the calling operation between functions.
01 # nested function
02 def sum(add, sub):
03 return add+sub
04 def sub(add, sub):
05 return add-sub
06 def function():
07 ex=1
08 ey=2
09 em=3
10 en=4
11 return sum(ex, ey) * sub(em, en)
13 print (function())
[Code Description]
The second line of code defines the function sum (), sum () with two
parameters a and b. Parameters a and b are used to calculate the value of
expression x+y.
The code in line 3 calculates the value of a+b, that is, returns the result of
X+Y.
The fourth line of code defines the function sub (), sub () with two parameters
a and b.
The code in line 5 calculates the value of a–b, i.e., returns the result of m–n.
The 11th line of code calls sum (), sub (), and performs multiplication in the
return statement.
Line 13 code, call function function ().
The output is shown below:
-3
Note that the number of nesting levels of functions should not be too high.
Otherwise, it is easy to cause problems such as poor readability and difficult
maintenance of the code. Nested calls to general functions should be
controlled within 3 levels.
The above code can also be implemented in another form, i.e., the functions
sum () and sub () are placed inside func ().
The following code implements the definition of sum (), sub () inside
function ().
01 # nested function
02 def function():
03 ex=1
04 yov=2
05 men=3
06 nod=4
07 def sum(am, bam): # internal function
08 return am+bam
09 def sub(am, bam): # internal function
10 return am-bam
11 return sum(ex, yov) * sub(am, bn)
13 print (function())
[Code Description]
In line 7, sum () is defined inside function ().
Line 9 code defines sub () inside function ().
Line 11 code, call sum () and sub () and then perform multiplication. The
output is "-3.”
Internal functions sum (), sub () can also directly call variables defined by
external function function ().
The following code implements the variables of the internal function sum (),
sub () that refer to the external function function ().
01 # nested function, directly using the variable
02 def function () of the outer function:
03 first= 1
04 second = 2
05 third = 3
06 fourth = 4
07 def sum(): # internal function
08 return first + second
09 def sub(): # internal function
10 return third - fourth
11 return sum() * sub()
13 print (function())
[Code Description]
In line 7, the function sum () has no parameters.
Line 8 code calls external variables x, y inside sum ().
In line 9, the function sub () also has no arguments.
Line 10 code calls external variables m, n inside sub ().
Line 11 code, calculate the value of sum()*sub (). The output result is "-3"
Be careful not to define functions inside them.
This method is not easy to maintain the program, and it is easy to cause
logical confusion. Moreover, the more levels of nested definition functions,
the higher the cost of program maintenance.
Recursive functions
Recursive functions can call themselves directly or indirectly within the
function body, that is, the nesting of functions is the function itself. Recursion
is a program design method. Recursion can reduce repeated codes and make
the program concise. The process of recursion is divided into two stages-
recursion and regression. The principle of the recursive function is as follows.
In the first stage, recursive functions call themselves internally. Each function
call restarts executing the code of the function until a certain level of the
recursive program ends.
In the second stage, recursive functions return from back to forth. Recursive
functions return from the last level until they are returned to the function
body called for the first time. That is, after the recursion step-by-step call is
completed, it returns step-by-step in the reverse order.
Note that recursive functions need to write conditions for recursion to end;
otherwise, the recursive program will not end. Generally, the program is
ended by judging the statement.
Calculating factorial is a classical recursive implementation. First of all,
review the calculation formula of factorial.
For example, calculate 5! As a result when designing a program, one can
judge whether n is equal to 1. Each recursive call passes in parameter n-1.
Until n=1, returns 1! is equal to 1. Then return to 2! 、 3! 、 4! 、 5!
Lambda function
Lambda function is used to create an anonymous function whose name is not
bound to the identifier. Using lambda function can return some simple
operation results.
Lambda functions have the following format:
Lambda variable 1, variable 2 ...: expression
Among them, the variable list is used for expression calculation. Lambda
belongs to a function, so a colon is required after the variable list. Lambda is
usually assigned to a variable, which can be used as a function.
For example:
01 # assignment
02 function=lambda variable 1, variable 2 ...: expression
# Call
04 function()
This binds lambda and variable function, whose name is the function name.
Lambda function can eliminate internal functions.
For example, the program for calculating (one+two) * (three–nfour) in
subsection can be modified to replace the functions sum (), sub () with
lambda functions.
01 # lambda
02 def func():
03 one = 1
04 two = 2
05 three= 3
06 four = 4
07 sum = lambda one, two : one + two
08 print (sum)
09 sub = lambda three, four : three - four
10 print (sub)
11 return sum(one, two) * sub(three, four)
13 print (function())
[Code description]
Line 7 defines the lambda function, realizes the calculation expression
first+second, and assigns the lambda function to the variable sum.
The eighth line of code outputs the value of the variable sum, which holds the
address of the lambda function.
The output is shown below:
<function <lambda> at 0x00B4D3B0>
Lines 9 and 10 have the same function as lines 7 and 8.
Line 11 calculates the product of sum () and sub (). The output is "-3.”
Note that lambda is also called an expression. Only expressions can be used
in lambda, and multiple statements such as judgment and loop cannot be
used. In the previous example, lambda is assigned to a variable and can also
be used directly as a function.
Function usage of lambda
01 # lambda
02 print ((lambda first: -first)(-2))
[Code Description]
The code in line 2 defines the anonymous function lambda x: -x, which is
used to return the absolute value of a number. The parameter of the function
is -2, and the output result is "2.”
By this, we have discussed in detail about functions and modules that are
important for software development using python. We will, in the next
chapter, discuss about object-oriented concepts in detail.
Chapter 6: Object-oriented Programming
in Python
Definition of category
In daily life, to describe a kind of thing, it is necessary to explain its
characteristics as well as its uses. For example, when describing such things
as human beings, it is usually necessary to give a definition or name to such
things. Human characteristics include height, weight, sex, occupation, etc.
Human behaviors include running, speaking, etc.
The combination of human characteristics and behaviors can completely
describe human beings. The design idea of an object-oriented program is
based on this design, which includes the features and behaviors of things in
classes. Among them, the characteristics of things are taken as the attributes
of classes, the behaviors of things are taken as the methods of classes, and
objects are an instance of classes.
So, to create an object, you need to define a class first. Class is composed of
3 parts.
(1) Class Name: The name of the class, whose initial letter must be
uppercase, such as Person.
(2) Attributes: used to describe the characteristics of things, such as people's
names, ages, etc.
(3) Method: Used to describe the behavior of things; for example, people
have behaviors such as talking and smiling.
In Python, you can use the class keyword to declare a class with the
following basic syntax format:
Class classname:
The property of the class
Method of class
The following is a sample code:
class Ox:
# attribute
# Method
def eat(grass):
Print ("-eating grass--")
In the above example, the class is used to define a class named Ox, in which
there is an eat method. As can be seen from the example, the format of the
method is the same as that of the function. The main difference is that the
method must explicitly declare a self-parameter and be located at the
beginning of the parameter list. Self represents the instance of the class
(object) itself, which can be used to refer to the attributes and methods of the
object. The specific usage of self will be introduced later with practical
application.
Construction method
In the case of a section, we dynamically added the color attribute to the
objects referenced by JB23. Just imagine, if you create another Plane class
object, you need to add attributes in the form of "object name.attribute
name.” For each object you create, you need to add attributes once, which is
obviously very troublesome.
To solve this problem, attributes can be set when creating an object. Python
provides a construction method with a fixed name of __init__ (two
underscores begin and two underscores end). When creating an instance of a
class, the system will automatically call the constructor to initialize the class.
In order to make everyone better understand, the following is a case to
demonstrate how to use the construction method for initialization.
# to define the class
2 class Plane:
3 # construction method
4 def __init__(autom):
Color = "black"
6 # honking
7 def toot(autom):
8 print ("%s plane is honking ..." (autom.color))
9 # creates an object and saves its reference with the variable plane
10 plane = Plane()
No.11 plane honked
12 plane.toot()
These lines re-implemented the __init__ () method, adding the color attribute
to the Plane class and assigning it a value of "black," and accessing the value
of the color attribute in the toot method.
Operation results
No matter how many Plane objects are created, the initial value of the color
attribute is "black" by default. If you want to modify the default value of the
property after the object is created, you can set the value of the property by
passing parameters in the construction method. The following is a case to
demonstrate how to use the construction method with parameters, as shown.
Example uses the parametric construction method. py
1 # Define Class
2 class Plane:
3 # belt parameter construction method
4 def __init__(autom, color):
Color = color6 # honking
7 def toot(autom):
8 print ("%s color plane honking ..." %autom.color)
9 # creates an object and saves its reference with the variable JB23
10 JB23 = Plane ("Snow White")
11 # creates an object and saves its reference with variable ferrari
12 ferrari = Plane ("red")
No.13 plane honked
14 JB23.toot()
15 ferrari.toot()
In examples, lines 4 to 5 customize the construction method with parameters
and assign the value of the parameters to the color attribute to ensure that the
value of the color attribute changes with the value received by the
parameters, and then it is still accessed in the toot method.
Destructural methods
Earlier, we introduced the __init__ () method. When an object is created, the
Python interpreter will call the __init__ () method by default. When deleting
an object to release the resources occupied by the class, the Python interpreter
calls another method by default, which is the __del__ () method.
Next, a case is used to demonstrate how to use destructor to release the
occupied resources, as shown.
Example uses the destructor. py
# Define Class
class Person:
def __init__(autom, name, age):
autom.name = name
autom.love = love
def __del__(autom):
Print ("-del----") laowang = person ("Lao Wang,” 30)
In the example, a class named Person is defined, the initial values of name
and age are set in the __init__ () method, a print statement is added in the
__del__ () method, and then an object of the Person class is created using a
custom construction method.
Thus we have given a brief introduction to object-oriented programming in
this chapter. In the next chapter, we will discuss Files in python in detail.
Come along with us to enjoy the final chapter of this book.
Chapter 7: Files in Python
This chapter will give a brief introduction to files in python. We will have
various examples that will help us understand the files, their structure, and
implementation.
Reading of files
There are many ways to read a file. You can use readline (), readlines (), or
Read () functions to read a file. The implementation method of reading files
by these functions will be introduced one by one.
1. readline ()
Readline () reads one line of the file at a time, and the file needs to be read
cyclically using a permanent true expression. However, when the file pointer
moves to the end of the file, there will be an error reading the file using
readline (). Therefore, a judgment statement needs to be added to the program
to judge whether the file pointer moves to the end of the file, and the loop is
interrupted by the statement. The following code demonstrates the use of
readline ().
01 # Use readline () to Read Files
02 f=open("rod.txt")
03 while True:
04 line=f.readline()
05 if line:
06 print (line)
07 else:
08 break
09 f.close()
[Code Description]
The code in line 3 uses "True" as the loop condition to form a permanent true
loop.
Line 4 calls readline () to read every line of the hello.txt file. Each cycle
outputs the following results in turn.
This is countryside
Line 5 code, judge whether the variable LINE is true. If true, the content of
the current line is output; otherwise, exit the loop. If the fourth line of code is
changed to the following statement, the reading method is slightly different,
but the reading content is exactly the same.
line=f.readline(2)
This line of code does not mean that only 2 bytes are read per line, but that
each line reads 2 bytes at a time until the end of the line.
2. Multi-line reading method readlines ()
To read a file using readlines (), you need to return the elements in the list by
looping through readlines (). The readlines () function reads multiple lines of
data in a file at once.
The following code demonstrates how readlines () reads a file.
01 # use readlines () to read files
02 f=file('rod.txt')
03 lines=f.readlines()
04 for line in lines: # read multiple lines at once
05 print (line)
06 f.close()
[Code Description]
The third line of code calls readlines () to store all the contents of the file
rod.txt in the list lines.
The fourth line of code loops through the contents of the list lines.
Line 5 code output list lines for each element
01 f=open("rod.txt")
02 context=f.read(5) # reads the first 5 bytes of the file
03 print (context)
04 print (f.tell()) # returns the current pointer position of the file object
05 context=f.read(5) # continue reading 5 bytes of content
06 print (context)
07 print (f.tell()) # output file current pointer position
08 f.close()
[Code Description]
The second line of code calls read(5) to read the contents of the first 5 bytes
in the hello.txt file and store it in the variable context. At this point, the
pointer of the file moves to the 5th byte.
The third line of code outputs the result of the variable context and the output
is "hello."
Line 4 calls tell () to output the current file
Line 5 code calls read(5) again to read the contents of bytes 6 to 10.
The output of line 6 is "world."
Line 7 code outputs the current file pointer position: 10.
Note that the location of the file pointer will be recorded inside the file object
for the next operation. As long as the file object does not execute the close ()
method, the file pointer will not be released.
Writing of files
The implementation of file writing also has many methods. You can use the
write (), writelines () methods to write files. It uses the write () method to
write strings to files, while the writelines () method can write the contents
stored in the list to files.
The following code demonstrates how to write elements in the list to a file.
01 # use writelines () to write files
02 f=file("rod.txt,” "w+")
03 li=["hello country side\n,” "hello city\n"]
04 f.writelines(li)
05 f.close()
[Code Description]
The second line of code uses the "w+" mode to create and open the file
hello.txt
Line 3 defines a list Li. Li stores 2 elements, each representing 1 line in the
file, and "\n" is used for line feed.
The fourth line of code calls writelines () to write the contents of list li into
the file.
The contents of the document are as follows.
hello countryside
hello City
The above two methods will erase the original contents of the file before
writing and rewrite the new contents, which is equivalent to "overwriting." If
you need to keep the original contents of the file and just add new contents,
you can open the file using mode "a+.”
The following code demonstrates the join operation of the file.
01 # Joins New Content to File
02 f=file("rod.txt,” "first+") # is written by joining a+
03 new_context="It is over"
04 f.write(getdetails)
05 f.close()
[Code Description]
The second line of code uses the mode "first+" to open the file hello.txt
The fourth line of code calls the write () method, the original contents of the
hello.txt file remain unchanged, and the contents of the variable getdetails are
written to the end of the rod.txt file. Txt is as follows.
hello countryside
hello City
goodbye
Writing files using writelines () is faster. If there are too many strings to write
to a file, you can use writelines () to improve efficiency. If only a small
number of strings need to be written, write () can be used directly.
Deletion of documents
The deletion of files requires the use of os modules and os.path modules. Os
module provides operating system-level interface functions for system
environment, files, directories, etc. File Handling Functions Commonly Used
in os Modules Note that the use of the OS module's open () function is
different from that of the built-in open () function.
The removal of the file needs to be implemented by calling the remove ()
function. Before deleting a file, it is necessary to determine whether the file
exists or not, if so, delete the file; otherwise, nothing will be done.
The following code demonstrates the deletion of the file:
01 import os
03 file("rod.txt,” "w")
04 if os.path.exists("rod.txt"):
05 os.remove("rod.txt")
[Code Description]
Line 3 code creates the file hello.txt
The fourth line of code calls the existing () of os.path module to determine
whether the file hello.txt exists.
Line 5 calls remove () to delete the file hello.txt
Reproduction of documents
The file class does not provide a method for directly copying files, but the
read () and write () methods can be used to copy files. The following code
copies the contents of hello.txt to hello2.txt.
01 # uses read (), write () to copy
Txt
03 src=file("rod.txt,” "w")
04 li=["hello world\n,” "hello US\n"]
05 src.writelines(li)
06 src.close()
07 # copy rod.txt to rod2.txt
08 src=open("rod.txt,” "r")
09 dst=open("rod2.txt,” "w")
10 dst.write(src.read())
11 src.close()
12 dst.close()
[Code Description]
Line 8 code opens the file hello.txt as read-only.
Line 9 code opens the file hello2.txt in a write-only manner.
In line 10, read () the contents of hello.txt, and then write these contents into
rod2.txt. Shutil module is another file and directory management interface,
providing some functions for copying files and directories. Copyfile ()
function can copy files.
The declaration of copyfile () function is as follows:
copyfile(src, dst)
[Code Description]
The parameter src represents the path of the source file and src is a string
type.
The parameter dst represents the path of the target file, and dst is a string
type.
This function copies the file pointed to by src to the file pointed to by dst.
The file can be cut using the move () function, which is declared as follows.
Renaming of files
The function rename () of the os module can rename files or directories. The
following code demonstrates the file renaming operation. If there is a file
named hello.txt in the current directory, rename it hi.txt; if there is a hi.txt
file, rename it hello.txt.
01 # Modify File Name
02 import os
03 li=os.listdir(.”")
04 print (li)
05 if "hello.txt" in li:
06 os.rename("hello.txt,” "hi.txt")
07 elif "hi.txt" in li:
08 os.rename("hi.txt,” "hello.txt")
[Code Description]
The third line of code calls listdir () to return the file list of the current
directory, where .”" indicates the current directory.
Thus, we have ended this book that explained a lot of python topics in detail
with the help of various examples. This is enough to start a small-medium-
level project which can help you implement all these concepts. Use GitHub to
find different python projects and start reading them. All the best for your
Coding Career. Cheers!
Conclusion
Thank you for making it through to the end of Python for beginners. Let’s
hope it was informative and able to provide you with all of the tools you need
to achieve your goals whatever they may be.
The next step is to implement these concepts to build coding projects and
software applications. We have discussed a lot of concepts from basics to
advanced stuff in detail.
Finally, if you found this book useful in any way, a review on Amazon is
always appreciated!
Python Machine Learning:
With the world going global, data science is the ultimate secret sauce of
technology, and it is on it that Artificial Intelligence lies. From predictive
analysis like weather forecast to pattern discovery, data science can produce
data from huge elements.
If you want to know more about data science, Python, and some of the fields
attached to it, this book will take you through the journey of technology. It
will discuss the importance as well as the benefits of data science to the
world. And as a fuel of any industry, you will read about how data science
impacts virtually all angles of the enterprise.
Away from data science and its applications, this book will discuss linear
algebra and why it is vital to prepare you to make an entrance into the
universe of machine learning. It will discuss in details every aspect of
machine learning, leading to the types of machine learning and their
algorithms as well as their use cases. The book will break the ground with the
discussion of Python, its benefits, learning Python with machine learning, and
ultimately, neural networks.
If you want to learn everything about Python, the details about its language,
the basic needs of machine learning, Python for data science, and so much
more, this book discuss some of these topics and many more.
In conclusion, thank you for picking up this book even when there are several
topics like this on the market. We went extra miles to package it with as
much information on Python for the beginner as much. And we believe that
you will have a good time reading it.
Chapter 1: What are Data Science and Deep
Learning?
There is an increasing need for storage of big data with the world going
global. Until 2010, this need has become the primary concern and challenges
of the enterprises. Building solutions and frameworks for data storage was a
critical focus. However, to process this data becomes the next focus since the
problem of building solutions and structures has been solved through
frameworks, particularly Hadoop, among others. Here, the secret sauce is
data science. Through data science, the science-fiction movies in Hollywood
can become an actual reality. And the imminent hope of Artificial Intelligent
is data science. As a result, understanding of data science and its benefits to
businesses is quite vital. As you read on, you will have an accurate
knowledge of the functions of data, its meaning in obtaining significant
insights from large and complex data sets in our environments and
surroundings.
Prescription analytics:
There will be a requirement for prescriptive analytics when you are set to get
a model that, through dynamic parameters, has the intellectual capacity of
modifying the decision it takes itself. Though it provides advice, it is a
comparatively recent discipline. In other words, apart from prediction, it
makes suggestions on a variety of given associated outcomes and actions. For
example, Google’s self-driving cars. To guide a self-driving vehicle, they
make use of the data they gather. And to bring intelligence to it, you can
process algorithms on this data. To this end, taking decisions is part of the
capacities of the car, including the path they must take, speed up or slow
down, and when to turn.
Phase 1 – Discovery:
Having a clear grasp of the variety of requirements, specifications, required
budget, and priorities of the project are vital. The capability to probe
uncertainties is a must. Next is the stage of assessment where you know
whether you possess the necessary resources, including supporting the project
with technology, people, data, and time. Also, formulating IH, that is, initial
hypotheses for analyzing and framing the problem of the business is required
in this stage.
Fraud detection
For fraud involving credit cards prevention and detection, insurance,
accounting, and so many more, data science application becomes crucial.
Banks are being proactive with the security of their employees and
customers. It is now faster for banks to resist activity on an account to
minimize losses since they detect fraud quickly. As a result, they have been
able to avoid significant loses and achieve necessary protection when they
implement a series of fraud detection schemes.
The fraud detection vital steps include:
Estimation of model
Getting data samplings for preliminary testing and model
estimation
Deployment and testing stage
Data scientists need to fine-tune and train individual data set since they are
different. There are demands for expertise in techniques of data-mining,
including forecasting, classification, association, and clustering, to transform
the in-depth theoretical knowledge into practical applications. For example,
the bank’s fraud protection system can put unusual high transactions on hold
pending the confirmation from the account holder. Algorithms of fraud
detection can also investigate multiple accounts opened in a short period with
the same data, or unusual high purchases of popular items of new accounts.
Customer data management
It is part of the obligations of the banks to analyze, store, or collect vast
numbers of data. With these data, data science applications are transforming
them into a possibility for banks to learn more about their customers. Doing
this will drive new revenue opportunities instead of seeing those data as a
mere compliance exercise. People widely use digital banking, and it is more
popular these days. The result of this influx produces terabytes of data by
customers; therefore, isolating genuinely relevant data is the first line of
action for data scientists. With the customers’ preferences, interactions, and
behaviors, then, data science applications will isolate the information of the
most relevant clients and process them to enhance the decision-making of the
business.
Personalized marketing
Providing a customized offer that fits the preferences and needs of particular
customers is crucial to success in marketing. Now it is possible to make the
right offer on the correct device to the right customer at the right time. For a
new product, people target selection to identify the potential customers with
the use of data science application. With the aid of apps, scientists create a
model that predicts the probability of a customer’s response to an offer or
promotion through their demographics, historical purchase, and behavioral
data. Thus, banks have improved their customer relations, personalize
outreach, and efficient marketing through data science applications.
Drugs creation
Involving various disciplines, the process of drug discovery is highly
complicated. Most times, the most excellent ideas pass through billions of
enormous time and financial expenditure and testing. Typically, getting a
drug submitted officially can take up to twelve years. With an addition of a
perspective to the individual stage of drug compound screening to the
prediction of success rate derived from the biological factors, the process is
now shortened and simplified with the aid of data science applications. Using
simulations rather than the “lab experiments,” and advanced mathematical
modeling, these applications can forecast how the compound will act in the
body. With computational drug discovery, it produces simulations of
computer model as a biologically relevant network simplifying the prediction
of future results with high accuracy.
Industry knowledge
To offer the best possible treatment and improve the services, knowledge
management in healthcare is vital. It brings together externally generated
information and internal expertise. With the creation of new technologies and
the rapid changes in the industry every day, effective distribution, storing,
and gathering of different facts is essential. For healthcare organizations to
achieve progressive results, the integration of various sources of knowledge
and their combined use in the treatment process is secure through data
science applications.
Downstream optimization
To process gas and crude oil, oil refineries use a massive volume of water.
Now, there is a system that tackles water solution management in the oil and
gas industry. Also, with the aid of distribution by analyzing data effectively,
there is an increase in modeling speed for forecasting revenues through
cloud-based services.
The Internet
Anytime anyone thinks about data science, the first idea that comes to mind
is the internet. It is typical of thinking of Google when we talk about
searching for something on the internet. However, Bing, Yahoo, AOL, Ask,
and some others also search engines. For these search engines to give back to
you in a fraction of second when you put a search on them, data science
algorithms are all that they all have in common. Every day, Google process
more than 20 petabytes, and these search engines are known today with the
help of data science.
Targeted advertising
Of all the data science applications, the whole digital marketing spectrum is a
significant challenge against the search engines. The data science algorithms
decide the distribution of digital billboards and banner displays on different
websites. And against the traditional advertisements, data science algorithms
have helped marketers get a higher click-through-rates. Using the behavior of
a user, they can target them with specific adverts. And at the same time and
in the same place online, one user might see ads on anger management while
another user sees another ad on a keto diet.
Website recommendations
This case is something familiar to everyone as you see suggestions of the
same products even on eBay and Amazon. Doing this add so much to the user
experience while it helps to discover appropriate products from several
products available with them. Leaning on the relevant information and
interest of the users, so many businesses have promoted their products and
services with this engine. To improve user experience, some giants on the
internet, including Google Play, Amazon, Netflix, and others have used this
system. They derived these recommendations on the results of a user’s
previous search.
Speech recognition
Siri, Google Voice, Cortana, and so many others are some of the best speech
recognition products. It makes it easy for those who are not in the position of
typing a message to use speech recognition tools. Their speech will be
converted to text when they speak out their words. Though the accuracy of
speech recognition is not certain.
Recommendation engine
This concept is one of the most promising and efficient, according to some
experts. In their everyday work, some central booking and travel web
platforms use recommendation engines. Mainly, through the available offers,
they match the needs and wishes of customers with these recommendations.
Based on preferences and previous search, the travel and tourism companies
have the ability to provide alternative travel dates, rental deals, new routes,
attractions, and destination when they apply the data-powered
recommendation engine solutions. Offering suitable provisions to all these
customers, booking service providers, and travel agencies achieve this with
the use of recommendation engines.
Route optimization
In the travel and tourism industry, route optimization plays a significant role.
It can be quite challenging to account for several destinations, plan trips,
schedules, and working distances and hours. With route optimization, it
becomes easy to do some of the following:
Time management
Minimization of the travel costs
Minimization of distance
For sure, data science improves lives and also continues to change the faces
of several industries, giving them the opportunity of providing unique
experiences for their customers with high satisfaction rates. Apart from
shifting our attitudes, data science has become one of the promising
technologies that bring changes to different businesses. With several
solutions the data science applications provide, it is no doubt that its benefits
cannot be over-emphasized.
Chapter 3: Probability – Fundamental –
Statistics – Data Types
Things are quite straightforward in Knowledge Representation and
Reasoning; KR&R. Exclusive of doubt, formulating and representing
propositions is easy. The thing is, when uncertainty makes itself known,
problems begin to arise – for example, an expert system designed to replace a
doctor. For diagnosing patients, a doctor possesses no formal knowledge of
treating the patient and no official rules based off of symptoms. In this
situation, to determine if the patient has a specific condition and also the cure
for it, it is the probability the expert system will use to formulate the highest
probability chance.
Strategies in sports
For competitions and games, the probability is what coaches and athletes
utilize to influence the best strategies for sports. When putting any player in
the lineup, a coach of baseball evaluates the batting average of such a player.
For example, out of every ten at-bats, an athlete may get a base hit two if the
player’s batting average is 200. The odd is even higher for a player to even
have, out of every ten at-bats, four hits when such a player has a 400-batting
average. Another example is when; field goal attempts from over 40 yards
out of 15, a high-school football kicker makes nine in a season, his next goal
effort from the same space may be about 60 percent chance. We can have an
equation like this:
9/15 = 0.60 or 60 percent
Insurance option
To conclude on the plans that are best for your family and even for you and
the required deductible amounts, probability plays a vital role in analyzing
insurance policies. For example, you make use of probability to know how
possible it can be that you will need to make a declaration when you choose a
car insurance policy. You may likely make consideration for not only liability
but comprehensive insurance on your car when 12 percent or of every 100
drivers over the past year, 12 out of them in your community have crashed
into a deer. Also, if following a deer-connected event run $2,8000, not to be
in a situation where you cannot afford to cover certain expenses, you might
consider a lower deductible on car repairs.
Statistics
The basis of modern science is on the statements of probability and statistical
significance. In one example, according to studies, cigarette smokers have a
20 times greater likelihood of developing lung cancer than those that don’t
smoke. In another research, the next 200,000 years will have the possibility
of a catastrophic meteorite impact on Earth. Also, against the second male
children, the first-born male children exhibit IQ test scores of 2.82 points.
But, why do scientists talk in ambiguous expressions? Why don’t they say it
that lung cancer is as a result of cigarette smoking? And they could have
informed people if there needs to be an establishment of a colony on the
moon to escape the disaster of the extraterrestrial.
The rationale behind these recent analyses is an accurate reflection of the
data. It is not common to have absolute conclusions in scientific data. Some
smokers can reduce the risk of lung cancer if they quit, while some smokers
never contract the disease, other than lung cancer; it was cardiovascular
diseases that kill some smokers prematurely. As a form of allowing scientists
to make more accurate statements about their data, it is the statistic function
to quantify variability since there is an exhibition of variability in all data.
Those statistics offer evidence that something is incorrect may be a common
misconception. However, statistics have no such features. Instead, to observe
a specific result, they provide a measure of the probability. Scientists can put
numbers to probability through statistic techniques, taking a step away from
the statement that someone is more likely to develop lung cancer if they
smoke cigarettes to a report that says it is nearly 20 times greater in cigarette
smokers compared to nonsmokers for the probability of developing lung
cancer. It is a powerful tool the quantification of probability statistics offers
and scientists use it thoroughly, yet they frequently misunderstand it.
Descriptive statistics:
With the use of measures for deviation like mean, median, and standard,
scientists have the capability of quickly summing up significant attributes of
a dataset through descriptive statistics. They allow scientists to put the
research within a broad context while offering a general sense of the group
they study. For example, initiated in 1959, potential research on mortality
was Cancer Prevention Study 1 (CPS-1). Among other variables,
investigators gave reports of demographics and ages of the participants to let
them compare, at the time, the United States’ broader population and also the
study group. The age of the volunteers was from ages 30 to 108 with age in
the middle as 52 years. The research had 57 percent female as subjects, 2
percent black, and 97 percent white. Also, in 1960, the total population of
female in the US was 51 percent, black was about 11 percent, and white was
89 percent. The statistics of descriptive easily identified CPS-1’s recognized
shortcoming by suggesting that the research made no effort to sufficiently
consider illness profiles in the US marginal groups when 97 percent of
participants were white.
Inferential statistics:
When scientists want to make a considered opinion about data, making
suppositions about bigger populaces with the use of smaller samples of data,
discover connection between variables in datasets, and model patterns in
data, they make use of inferential statistics. From the perspective of statistics,
the term “population” may differ from the ordinary meaning that it belongs to
a collection of people. The larger group is a geometric population used by a
dataset for making suppositions about a society, locations of an oil field,
meteor impacts, corn plants, or some various set of measurements
accordingly.
With regards to scientific studies, the process of shifting results to larger
populations from small sample sizes is quite essential. For example, though
there was conscription of about 1 million and 1.2 million individuals in that
order for the Cancer Prevention Studies I and II, their representation is for a
tiny portion of the 1960 and 1980 United States people that totaled about 179
and 226 million. Correlation, testing/point estimation, and regression are
some of the standard inferential techniques. For example, Tor Bjerkedal and
Peter Kristensen analyzed 250,000 male’s test scores in IQ for personnel of
the Norwegian military in 2007. According to their examination, the IQ test
scores of the first-born male children scored higher points of 2.82 +/- 0.07
than second-born male children, 95 percent confidence level of a statistical
difference.
The vital concept in the analysis of data is the phrase “statistically
significant,” and most times, people misunderstand it. Similar to the frequent
application of the term significant, most people assume that a result is
momentous or essential when they call it significant. However, the case is
different. Instead, an estimate of the probability is statistical significance that
the difference or observed association is because of chance instead of any
actual connection. In other words, when there is no valid existing difference
or link, statistical significance tests describe the probability that the
difference or a temporary link would take place. Because it has a similar
implication in statistics typical of regular verbal communication, though
people can measure it, the measure of significance is most times expressed in
terms of confidence.
Data Types
To do Exploratory Data Analysis, EDA, you need to have a clear grasp of
measurement scales, which are also the different data types because specific
data types have correlated with the use of individual statistical measurements.
To select the precise visualization process, there is also the requirement of
identifying data types with which you are handling. The manner with which
you can categorize various types of variables is data types. Now, let’s take an
in-depth look at the main types of variables and their examples, and we may
refer to them as measurement scales sometimes.
Categorical data
Characteristics are the representation of categorical data. As a result, it stands
for things such as someone’s language, gender, and so on. Also, numerical
values have a connection with categorical data like 0 for female and 1 for
male. Be aware that those numbers have no mathematical meaning.
Nominal data
The discrete units are the representation of nominal values, and they use them
to label variables without any quantitative value. They are nothing but
“labels.” It is important to note that nominal data has no order. Hence,
nothing would change about the meaning even if you improve the order of its
values. For example, the value may not change when a question is asking you
for your gender, and you need to choose between female and male. The order
has no value.
Ordinal data
Ordered and discrete units are what ordinal values represent. Except for the
importance of its ordering, ordinal data is therefore almost similar to nominal
data. For example, when a question asks you about your educational
background and has the order of elementary, high school, undergraduate, and
graduate. If you observe, there is a difference between college and high
school and also between high school and elementary. Here is where the major
limitation of ordinal data suffices; it is hard to know the differences between
the values. Due to this limitation, they use ordinal scales to measure non-
numerical features such as customer satisfaction, happiness, etc.
Numerical Data
Discrete data
When its values are separate and distinct, then we refer to discrete data. In
other words, when the data can take on specific benefits, then we speak of
discrete data. It is possible to count this type of data, but we cannot measure
it. Classification is the category that its information represents. A perfect
instance is the number of heads in 100-coin flips. To know if you are dealing
with discrete data or not, try to ask the following two questions: can you
divide it into smaller and smaller parts, or can you count it?
Continuous data
Measurements are what continuous data represents, and as such, you can only
measure them, but you can’t count their values. For example, with the use of
intervals on the real number lines, you can describe someone’s height.
Interval data
The representation of ordered units with similar differences is interval values.
Consequently, in the course of a variable that contains ordered numeric
values and where we know the actual differences between the values is
interval data. For example, a feature that includes a temperature of a given
place may have the temperature in -10, -5, 0, +5, +10, and +15. Interval
values have a setback since they have no “true zero.” It implies that there is
no such thing as the temperature in regards to the example. Subtracting and
adding is possible with interval data. However, they don’t give room for
division, calculation, or multiplication of ratios. Ultimately, it is hard to apply
plenty of inferential and descriptive statistics because there is no true zero.
Ratio data
Also, with a similar difference, ratio values are ordered units. The contrast of
an absolute zero is what ratio values have, the same as the interval values.
For example, weight, length, height, and so on.
Statistical Methods
Nominal data
The sense behind dealing with nominal data is to accumulate information
with the aid of:
Frequencies:
The degree upon which an occasion takes place concerning a dataset or over
a period is the frequency.
Proportion:
When you divide the frequency by the total number of events, you can easily
calculate the proportion. For example, how often an event occurs divided by
how often the event could occur.
Percentage:
Here, the technique required is visualization, and a bar chart or a pie chat is
all that you need to visualize nominal data. To transform nominal data into a
numeric feature, you can make use of one-hot encoding in data science.
Ordinal data
The same technique you use in nominal data can be applied with ordinal data.
However, some additional tools here there for you to access. Consequently,
proportions, percentages, and frequencies are the data you can use for your
summary. Bar charts and pie charts can be used to visualize them. Also, for
the review of your data, you can use median, interquartile range, mode, and
percentiles.
Continuous data
You can use most techniques for your data description when you are dealing
with constant data. For the summary of your data, you can use range, median,
percentiles, standard deviation, interquartile range, and mean.
Visualization techniques:
A box-plot or a histogram, checking the variability, central tendency, kurtosis
of a distribution, and modality all come to mind when you are attempting to
visualize continuous data. You need to be aware that when you have any
outliers, a histogram may not reveal that. That is the reason for the use of
box-plots.
Descriptive Statistics
As an essential aspect of machine learning, to have an understanding of your
data, you need descriptive statistical analysis since making predictions is
what machine is all about. On the other hand, as a necessary initial step, you
conclude from data through statistics. Your dataset needs to go through
descriptive statistical analysis. Most people often get to wrong conclusions by
losing a considerable amount of beneficial understandings regarding their
data since they skip this part. It is better to be careful when running your
descriptive statistics, take your time, and for further analysis, ensure your
data complements all prerequisites.
Normal Distribution
Since almost all statistical tests require normally distributed data, the most
critical concept of statistics is the normal distribution. When scientists plot it,
it is essentially the depiction of the patterns of large samples of data.
Sometimes, they refer to it as the “Gaussian curve,” or the “bell curve.”
There is a requirement that a normal distribution is given for calculation and
inferential statistics of probabilities. The implication of this is that you must
be careful of what statistical test you apply to your data if it not normally
distributed since they could lead to wrong conclusions.
If your data is symmetrical, unimodal, centered, and bell-shaped, a normal
distribution is given. Each side is an exact mirror of the other in a perfectly
normal distribution.
Central tendency
Mean, mode, and the median is what we need to tackle in statistics. Also,
these three are referred to as the “Central Tendency.” Apart from being the
most popular, these three are distinctive “averages.”
With regards to its consideration as a measure that is most consistent of the
central propensity for formulating a hypothesis about a population from a
particular model, the mean is the average. For the clustering of your data
value around its mean, mode, or median, central tendency determines the
tendency. When the values’ number is divided, the mean is computed by the
sum of all values.
The category or value that frequently happens contained by the data is the
mode. When there is no repletion of number or similarity in the class, there is
no mode in a dataset. Also, it is likely for a dataset to have more than one
mode. For categorical variables, the single central tendency measure is the
mode since you can compute such as the variable “gender” average.
Percentages and numbers are the only categorical variables you can report.
Also known as the “50th percentile,” the midpoint or “middle” value in your
data is the median. More than the mean, the median is much less affected by
skewed data and outliers. For example, when a housing prizes dataset is from
$100,000 to £300,000 yet has more than $3million worth of houses. Divided
by the number of values and the sum of all values, the expensive homes will
profoundly impact the mean. As all data points “middle” value, these outliers
will not profoundly affect the median. Consequently, for your data
description, the median is a much more suited statistic.
Chapter 4: Linear Algebra
Example 1:
Imagine the perception you have when you attempt to take in the picture of a
flower. Well, it is easy since you can make out leaves and flower. However,
it can be such a challenging task when, for the computer to engage in the
same job, you are asked to mark that logic. Since the brain of human has
passed through evolution for millions of years, you can identify the flower.
To have the power of telling if the color of an image is black or red, we have
no clue of the things that go on in the background. To perform the task is the
only our brains have been trained to do.
However, it is a difficult task to make a computer engage in a similar
mission, and it is a dynamic feature of study in computer science and
machine learning in general. We may need to reflect on a specific question
ahead of making identification of image attributes; so, what is the process of
storing this image by a machine?
To prepare the single 0 and 1 is how they design computers nowadays.
Therefore, how can they store such an image inside a network with various
attributes like the color? The accomplishment of this storage is through the
construct containing the intensities of pixel known as Matrix. As a result, it is
in the capacity of how they process this matrix to make out colors and some
other things. At the back end will all the operation anyone wants to carry out
on this stage will happen using matrices and linear algebra.
Example 2:
Have you heard the term “XGBOOST?” Any domain of data science domain
household knows that data science competitions winners employ quite often
an algorithm. To give predictions, it takes the Matrix form to store the
numeric data. Not only does it offer more precise results, but XGBOOST is
also capable of faster data process. Furthermore, apart from XGBOOST,
other numerous algorithms make use of Matrices for data processing and
storage.
Example 3:
As the latest catchword around now, deep learning uses matrices for storing
inputs, including giving topnotch answers to these questions using text or
speech or image. Also stockpiled in the matrices are weights that a neural
network trained.
Example 4:
Dealing with text is one more dynamic field of machine learning research,
and term-document matrix, words’ bag, and so on are some of the techniques
they frequently use. In the same manner, to perform tasks such as language
translation, language generation, semantic analysis, and so many others, all
these methods store counts of words within documents and to perform tasks,
accumulate this occurrence count in a matrix form.
Thus, let’s hope that, to some extents, you have had some understanding of
machine learning and its connection with linear algebra. To employ matrices
for data processing and storage, we know the text, image, or any general data.
It is now time to experience the linear algebra from the top.
Planes
The three variables in a linear equation, whose coordinates satisfy the
equation, represent the set of all points. By such an equation, can you
decipher its physical representation? Attempt to image 2 variables, while
adding the third one, in the same instance in any comparison. As you should
know, it is a three-dimensional analog of line and that it represents. Indeed,
the representation of a plane is three variables of a linear equation. Three
variables represent a plane in a linear equation. More precisely, extending up
to infinity, a plane is a flat geometric object.
It indicates that we desire to unearth the connection of those planes on the
instance of a line by finding solutions to 3 variables linear equation. If you
look deeply, in which ways can a group of three planes intersect? Let’s see if
things are possible in these four cases;
1. The intersection is not present
2. The intersection of the three planes at a point
3. In a line, the intersection of planes
4. Intersection happens with a plane
Most of the super mathematicians and regular individuals like us can only
visualize things in 3-Dimensions, and it is complicated unachievable for
humans to visualize things in 4 (or 10000) dimension. Therefore, how is it
possible for mathematicians to effectively tackle data of higher proportion? In
their heads are tricks and one such ploy mathematicians utilize to take care of
data of larger size is matrices.
Right away, it’s time to move on to the main focus, which is the matrix.
Matrix
Matrix is the process of writing the same items collectively for our necessity
to manipulate and handle them. In data science, while training several
algorithms, the matrix is what they use to accumulate information such as
how an artificial neural network stores weights. Technically, as far as data
science is concerned, a 2-D collection of numbers is a matrix.
1 2 3
4 5 6
7 8 9
Usually, ‘i’ denotes rows and ‘j’ denotes column. The i’th row indexes the
elements and the jth column. Through some alphabet like elements of A by A
(ij), we mean the matrix.
In the matrix above;
A12 = 2
Reach the second column after getting along the first row to get the result.
Loss
The difference between the actual output value and the output value that our
model predicts or the rate of the error is the function of the loss. Minimizing
the function of loss is quite vital for us to solve a problem.
Task
The thing we must do with the given data is what the task specifies for us.
Task depends on the questions one has to solve with the available
information. For example, based on the data, you can design a task to
measure the happiness level of the employee or the performance of the
employee.
Data
The fuel of machine learning is data, and you must learn to provide a proper
history of data on the output and input. For example, an HR needs to give
provision of all the employee information to have a prediction on whether or
not an employee stayed or left or will leave the company.
Evaluation
We need to see the accuracy of the model to resolve the problem that we aim
it to solve by identifying how well our model performs.
Accuracy = number of correct predictions/total number of predictions
When you test with some parts data, you can identify the precision that we
gathered initially but make no use of it to train the model.
Model
The machine generates a formula that maps output and input or a model
based on the data and input we provide. Where (x) is input and (y) is the
output, a model can be like anyone of these equations;
Linear function:
When the graph of the function graph is a straight line, then we have linear
function. We have linear function when any x1, x2……………, xN, the
exponent of variables is comes to be 0 or 1. f(x,y) = x+y+1, f(x) = x+1, f(x)
=2 are a few examples of the linear functions.
As you will see, the function of the graph below is linear since it has a
straight line and it is the graph for f(x) = x+1.
f(x)=x+1 graph
Non-Linear function:
When the function graph is not a straight line, then we have the non-linear
function. Also known as non-linear function, the exponents of the variables in
the function are older than 0 or 1. Some examples of the non-linear function
are f(x) = x3, f(x) = x2. The graph below is not a straight line and therefore, is
for f(x) =x2, showing the non-linear function.
The attempt to identify this function f(x1, x2…….., xN) is what we are trying
to do in supervised machine learning, where the features are x1, x2……..,
xN. Based on the data we are dealing with, this function could be anything
linear or non-linear. To predict the output for us, when we obtain this
function, then, we feed on the features. There are two types of supervised
machine learning, depending on the output type.
Regression:
There is a regression problem when the output value is continuous. For
example, we may call it regression since weight is a constant value when we
are attempting to predict the weight of a person based on features like height.
Classification:
The classification problem is the process of the output value being discrete.
For example, when a bank establishes the prediction of whether an individual
is a fraud or not on specific features, then, the classification problem is this
type of problem. Also, classifying the breed a dog belongs to is another
excellent example of a classification problem.
Logistic Regression
As an extension of the linear regression model for classification problems and
with two likely results, logistic regression models the probabilities for
classification problems. Logistic regression is the solution for classification.
To press a linear equation output between 0 and 1, it is the function of
logistic rather than fitting a hyper-plane or straight line that the logistic
regression model uses. The definition of the logistic function is as follows:
1
logistic( η ) =
1 + exp(- η)
^ y ( i )= β 0+ β 1 x ( i )1+…+ βpx ( i ) p
The model
With the features, x_0 through x_n and classes c_0 through c_k, the goal of
any probabilistic classifier is not only to return the most likely type, but also
to determine the probability of the features happening in each category.
Consequently, we may wish to have the capacity to calculate P(c_i / x_0,
…….., x_n for each group. The Bayes rule is what we use to do this. Bayes
rule has this feature;
When you calculate the individual P(x_j / c_i) terms will depend on what
distribution your features follow. Where the elements may be word counts, in
the text of word classification, features may follow a multinomial
distribution. In other cases, they may develop a Gaussian distribution where
features are continuous.
K – Means
Without any target labels, K-means is an unsupervised learning algorithm
that gives the ability to identify the same groups or clusters of data points
within your data. Where assignment to the clusters is based on some distance
or similarity measure to a centroid by grouping the data into K clusters is the
issue with K means. Now, how do we solve this issue? It is okay if we could
outline the steps involved.
1. To its nearest centroid is where each data point is assigned when
we initiate the K starting centroids, and this process is what we can
do randomly.
2. Attached to the respective cluster, we compute the centroids as the
mean of the data points.
3. Pending the moment we can induce our stopping criteria, steps 1
and 2 is what we will do.
To be more precise, it is for squared Euclidean distance or Euclidean distance
that we are attempting to optimize for in case you are wondering what is
happening. To the cluster that minimizes this squared distance or groups
closest to them is where they assign the data points. As it is written formally
like this:
For each data point to its assigned cluster, J is simply the sum of squared
distances. Where (x_n), the data point, is attached to the (k) cluster, and 0
otherwise, an indicator function, r is equal to 1.
Support Vector Machine (SVM)
As an algorithm of a supervised machine learning algorithm, they use support
vector machine for regression or challenges in classification. But it is in
classification problems that they mostly use it. We design an item of each
data in this algorithm as a tip in the space of n-dimension, where the features
number you have is n, with the value of an individual coordinate as the same
as the value of each feature. Then, through obtaining the hyper-plane which
differentiates both classes quite well enough, we perform classification.
Decision Trees
For prediction and classification, decision trees are the most popular and
powerful tools. Similar to the structure of the tree, a decision tree is like a
flowchart, where a test result is the representation of each branch, where
terminal node, i.e., each leaf node contains a set label, and each internal node
denotes a test on an attribute. Decision trees have some strengths which
include understandable rules generation, requiring little computation to
execute classification, provision of a comprehensible clue of which domains
are a primarily significant classification or prediction, and ability to handle
both continuous and categorical variables. Where the purpose is to predict a
constant characteristic value, weaknesses of decision trees include the fact
that they are less appropriate for estimation tasks, and with reasonably
insignificant quantity and many classes of training samples, are prone to
errors in classification problems.
Random Forest
The random forest grows several classification trees. All you need to do is to
place the input vector down each of the trees in the forest to classify a new
object from an input vector. When we say that the tree “votes” for that class,
we are saying that each tree gives a classification. Overall the trees in the
forest, the forest decide the categorization that has the most votes. The
random forest grows each tree as follows:
The sample of N cases at random – however with replacement,
from the original data if the training set is N for the number of
cases. For growing the tree, this model will be the collection of
training.
With the best split on these M is used to split the node, a number
m<<M, which is M input variables, is specified such that at each
node, m variables are randomly picked out of the M. In the course
of the forest growing, the M value is assumed.
Since no pruning is likely; each tree can grow to the most
extensive degree on the cards.
Gradient Boosting
By attempting to understand what boosting is, we can correctly define
gradient boosting. The technique of converting weak learners into active
learners, we are talking of boosting. In boosting, a modified version of the
unique data set is a fit on each new tree. Hence, several models get their
training from gradient boosting in a sequential, additive, and gradual
approach. Utilizing the two algorithms distinguishing the weak learners’
shortcoming, such as decision trees are the main distinction between gradient
boosting algorithm and AdaBoost. Whereas the gradient boosting runs
similar operation with the use loss function gradients (y = ax + b + e,
because it is the term of error, e needs a special mention), the AdaBoost
model identifies the shortcomings by high weight data points.
Chapter 6: Types of Machine Learning
Even though this chapter will be talking about types of machine learning, you
may come across some parts that we have discussed earlier in the last chapter.
But this chapter goes more in-depth into this same excellent subject called
machine learning.
You see, machine learning has made huge impacts by amplifying multiple
elements of the business operation, becoming a diverse and reliable business
tool from a science fiction fancy. With the implementation of its algorithms
essential for the maintenance of competitiveness in several industries and
fields, the influence of machine learning on the performance of companies is
quite significant. Requiring a lot of resources, machine learning
implementation into the operations of the business is a tactical measure. As a
result, understanding various perks different machine learning algorithms
bring to the table and your desired work for the machine learning.
As you read on, not only will you know the great purpose of the algorithms
of machine learning, but you will also have an in-depth insight into the
machine learning algorithms’ significant types.
Classification:
In a case where the algorithm obtains a manual training when you label
incoming data based on the samples of the past data, not only categorize
specific types of objects accordingly but to also recognize particular kinds of
objects is the process of classification. Whether to perform a binary
recognition, an optional image, and character, in a situation where there is
compliant or non-compliant of a bit of data to individual requirements in a
true or false approach, it is in the power of the system to know how to
differentiate types of information.
Regression:
For you to calculate and identify continuous outcomes is the process of
regression. Not only the groupings such as widths, heights, and so on but also
their values are what the system is supposed to understand, as well as the
numbers and their significance.
Some of the algorithms that are widely used include:
Support vector machines
Linear regression
Nearest neighbors
Logistical regression
Random forest
Decision trees
Gradient boosted trees
Neural networks
Naive Bayes
Use cares of supervised learning algorithms
Trend forecasting in retail commerce, stock trading, and sales, as well as
price prediction, is supervised learning’s mainly universal fields of use. For
the two situations, to calculate possible outcomes and assess the possibility,
the algorithm utilizes incoming data. Highspot and Seismic are the platforms
of sales enablement that make use of this type of an algorithm by looking for
consideration while presenting scenarios from several angles.
As the sequence of ad content delivery component, ad tech operation is part
of business cases for supervised learning. The algorithm of supervised
learning has the role of keeping the spending of the budget under particular
margins such as overall budget for a specific period or a single purchase price
scope, and also assessing possible prices of ad spaces and its value in the
course of the real-time bidding process.
Clustering:
Based on their internal patterns devoid of prior knowledge of group
credentials and used to segment it into meaningful groups, that is, clusters,
the process of clustering is simply data exploration. The individual data
objects similarity defines the credentials and the test as well as used for
anomalies detection features of its dissimilarity.
Dimensionality reduction:
With the incoming data, the noise is so overwhelming. Even while distilling
the pertinent information and for the removal of this noise, the algorithm of
machine learning makes use of dimensionality reduction.
Hence, the algorithms that developers use widely include:
K – means clustering
t – Distributed Stochastic Neighbor Embedding, T - SNE
Association rule
Principal Component Analysis, PCA
Unsupervised learning machine used cases
For a maximum impact, the domains where they use unsupervised learning
are ad-tech and digital marketing. Also, in most cases, for them to make
befitting adjustment of the service while exploring the customer information,
they apply the use of this algorithm. Indeed, in the incoming data, the fact is
plenty of self-styled “known unknowns.” exist. Having the power for the
extraction of appropriate foreknowledge out of unlabeled data while they
make sense of it is the actual effectiveness of the business operation.
The data management of the recent gets itself ready through the unsupervised
algorithms. This algorithm of machine learning has its implementation
among the most cutting-edge platforms of data management like Salesforce
and Lotame at the moment. Thus, with the use of specific credentials,
including the setting of particular software, personal data elements,
behavioral data, and so on, they can use unsupervised learning to identify
target audience groups. Also, for the campaign performance patterns
identification, as well as ad content, they can use this algorithm to develop
more efficient targeting.
Python –V
From the Python Software Foundation, you may need to download Python if
you are running Windows.
Features of Python
Most times, as a language that is object-oriented and incredibly powerful,
Python is comparable to PHP, Ruby, Perl, Java, and Scheme. For developers,
it is quite an exciting working with this language with some of the several
notable features of Python including:
1. It is much easier to read the programs any developers write
because Python makes use of an elegant syntax. They quite come
close to the manner with which we write our words which is closer
to the language of the humans, rather than code interpretation, a
style that computers use to study. For example, at runtime, and
while in quotes, the command of “print” will display anything
preceding it.
2. Getting your program up and running is more comfortable with
Python since it is easy and straightforward to use. Similar to ad-
hoc programming skills, the consideration for Python is that it is
ideal for the development of the prototype. Also, it has no
compromise maintainability.
3. With the provision of incorporated maintenance for various general
programming undertakings such as files modification, searching
through text, and syncing with the web browser, Python has
Standard Python Library. Your content may have to be developed
from scratch for a majority of other languages.
4. For the simplification of testing for short snippets of code, there is
an inclusion of an interactive mode. You will also have IDLE, a
development setting, and it is faster and easier with the help of the
development environment.
5. Even if you have already compiled them in C or C++, there is an
opportunity of extending the language by adding new modules.
Even better, once you have created them in future projects, you can
use the modules as shortcuts.
6. Through the provision of a programmable users’ interface of an
app, you can also embed Python into an application. If you are
developing an app in a terminal that has the requirement of running
with Python or that will teach coding, this dynamic is a great
feature.
7. Python has compatibility with several operating systems and
computers such as MacOs, Linux, Windows, OS/2, several Unix
brands, and so on. Also, if necessary, you can quickly jump
between them since the interface of Python is the same as each of
those platforms.
8. As there is no licensing fee and to download and use it will not
cost you any penny and use, Python is genuinely free. Also, even
though it is copyrighted, and since it is under an open-source
license that the language is available, you can freely redistribute or
modify it.
What is Django?
Written in Python, Django is an open-source and free web application
framework. A collection of modules is a framework that makes development
easier. Instead of creating from scratch, since they are in a group, they allow
you to create websites and applications from an existing source. Websites, no
matter if one person designs them, can have functionality such as
management and admin panels, authentication support, comment boxes, file
upload support, contact forms, and so many more. In other words, you may
need to develop these components yourself if you were creating a website
from scratch. Rather than using a framework, you only need to configure
them properly to match your site since these components are already built.
You can use a big collection of the modules Django provides in your
projects. Significantly, developers can save a lot of time and headaches by
using frameworks, and Django is also part of them. Also, it might interest
you that they create Django with front-end developer in mind. For those that
are familiar with working with HTML, such as front-end developers and
designers, they will feel comfortable with Django’s template language, which
is easy to learn. However, developers can as well augment the template
language as they want with its highly extensible and flexible features.
You will want to remember the framework of Django if you are going to be
working with Python, particularly for web design or web applications.
Indeed, it will come in handy. Though they designed it with the complete
minimalist in mind, another framework that is great to work with is Python-
based is CherryPy. When you have some experience working with Python,
CherryPy is a framework you will want to explore.
The age of data that we live in can only be enriched with more storage
resources and better power of computation. As there is a rise in the
information or data every day, making sense of all the data is the real
challenge. By developing intelligent systems that use the methodologies and
concepts from machine learning and data mining, organizations and
businesses are attempting to tackle the situation. Among them, the most
exceptional field of computer science is machine learning. We will be on the
right path if our defining factor for machine learning as the science and
application of algorithms that offer a sense of the data.
Dynamic circumstances
We have the nature of dynamic in some situations, i.e., over time; they are
changing. We may require the machine to take a data-driven decision as it
learns in behaviors or conditions such as this. For example, the availability of
infrastructure in a company and network connectivity.
Strengths
As some surveys and research indicate, the most popular language, as well as
the fifth most significant language for data science and machine learning, is
Python. Some of the strengths that give Python these fair shares include:
Easy to understand and learn – Python’s syntax is more straightforward.
As a result, learning and understanding the language is relatively easy, even
for beginners.
Multi-purpose language – since it has excellent support for structured
programming, Python is a multi-purpose programming language, with added
support for functional programming and object-oriented programming.
A considerable number of modules – for developers to cover all features of
programming, Python gives them a massive amount of modules. And it
makes Python an extensive language since these modules are available easily
for use.
Open-source community support – Python has the broad support of a large
developer community since it is an open-source programming language.
Because of this good advantage, the Python community quickly fixes the
bugs. Python is adaptive and robust because of this characteristic.
Scalability – since it makes provision of an improved structure for
supporting large programs than shell-scripts, Python is a scalable
programming language.
Weakness
While it may be a powerful and popular programming language, slow
execution speed is the weakness of Python. With comparison to compiled
languages since Python is an interpreted language, the execution speed of
Python is slow. For the Python community, this situation can be the primary
area of improvement.
Easy prototyping
Fast and easy prototyping is another essential feature of Python, which makes
it the choice of language for data science. While on the developing stage of
the new algorithm, this feature can be useful.
Collaboration feature
Good collaboration is quite critical in the field of data science, and this
situation is straightforward with several useful tools that Python provides.
Clustering
Unsupervised classification is clustering. With no availability of labeled data,
this classification is an analysis of exploratory data. When we make use of
clustering, we are doing the process of separating data that are unlabeled into
discrete and finite collections of data composition that are hidden and natural.
Here are two types of clustering for your observation:
Hard clustering – a single cluster fits in with one object
Soft clustering – multiple groups belong to one object
Designing the clustering algorithm after selecting the features and then
validate the clusters are the first steps in clustering. As a result, interpreting
the outcomes is what we do in conclusion.
Anomaly detection
Something that has a deviation from its predictable pattern is an anomaly.
Spotting an outlier is something we may sometimes wish with machine
learning. For example, we may want to detect per hour bill of a dentist for 85
fillings. Per patient, the seconds are 42. Finding the bill of a specific dentist
just for Tuesdays is another example. Suspicion may arise from these
situations and to emphasize on these anomalies, and since it is not what we
are looking for specifically for, we can use anomaly detection.
File header
Each file in CSV data files contains the information for each field in the
header. For the data file and the header file, it is imperative to make use of
similar delimiter since how we should interpret data fields is what the header
file specifies. Here are some of the cases common to file header of CSV that
need proper consideration:
Case 1: where a file header is in data file – when a file header is as
a result of the data file, each column of data will automatically get
assigned the names.
Case 2: where a file header has no data file – when there is no file
header in the data file, it is with a manual approach that each
column of data will be assigned names.
Whether our CSV file contains a header or not in the two scenarios, there is a
need to have an explicit explanation on this.
Comments
With comments in any data file, there is now a significant implication. At the
beginning of the line in the data file of CSV, the indication of comments is
through a hash (#). In the process of loading into machine learning projects
the CSV data, there must be a consideration for comments since, depending
upon the method we choose for loading, we may have to indicate whether to
expect those comment or not if the file contains comments.
Delimiter
The standard delimiter in the data files of CSV is comma (,) character.
Separating the standards in the domains is the purpose of delimiter. As a
result, while uploading the CSV file into a machine learning project, and
because we can make use of a different delimiter like white space or tab,
considering the delimiter’s purpose is essential. However, we need to give it
an explicit specification if we want to use another delimiter than the standard
one.
Quotes
The default quote character is double quotation (“ “) mark in CSV data file.
Again, as we attempt to upload the CSV file into a machine learning project,
we must consider the purpose of quotes so we can use other quote characters
than double quotation mark. However, there is a need to be clear when we are
using a different quote style other than the standard quote.
function.
Product recommendations
Jabong and Amazon are some of the shopping platforms that suggest similar
products to you when they notice what products you look at with your
experience using their platforms. For them, it is a win-win situation since you
are likely to make a purchase when they show you some favorite products to
you. Also, they use a cart and wishlist content for this.
Automatic translation
We have the luxury of translating text into another language through machine
learning. How words fit together and thus uses this information to improve
the quality of a translation is what the machine learning algorithm for these
tackles. Also, people can translate the text on images with the use of neural
networks to identify letters with automatic translation.
Video surveillance
If it is possible to be aware of some crimes, people can avoid them. Through
a video surveillance system, people will be mindful of the behaviors of others
toward someone else, a situation, or a place.
Chapter 9: K – Nearest Neighbor
Algorithms – K – Means Clustering
K – Nearest Neighbors
In close proximity, the existence of similar things as an assumption is the
sum of the algorithm of KNN. Furthermore, close to each other, similar
objects are in the same surrounding. For the algorithm to be functional, the
concept of the KNN is that assumption is sufficiently accurate. Sometimes
referred to as closeness, proximity, or distance, the idea of similarity captures
KNN with some mathematics some of us might have learned in our
childhood, which is to calculate the distance between points on a graph.
We have various ways of calculating distance, and depending on the problem
we are trying to solve, one of them might be preferable. However, the
standard and popular choice is the Euclidean distance, which is the straight-
line distance.
Similarity
Between any two given data instances, we need to calculate their similarity so
we can make predictions. For an assigned member of the test dataset and
sequentially make a prediction, doing this is quite crucial for us to locate the
K most related data instances in the training dataset.
The Euclidean distance measure is what we can use if the units of all four
measurements of the flower are the same and are numeric. Between the two
sets of numbers, this defines as the square root of the sum of the squared
differences. At least for a few more times, you may want to let that sink in by
rereading it. Also, the inclusion of which field in the calculation of distance
calculation is another thing we want to control. Specifically, to contain the
first 4 attributes is what we only want. While ignoring the final dimension,
then to a fixed length with one approach, you need to limit the Euclidean
distance. You can make the Euclidean Distance definition when you put all of
this together.
Neighbors
Now we can use a measure of similarity that for a given unseen instance, we
have to collect the K most similar cases. For subset selection with the values
of the smallest distance and calculating the range for all the circumstances,
this process is a straightforward one.
Response
Based on these neighbors, what we have to do next is to devise a predicted
response after locating the neighbors that are most similar for an instance of
test. This can be achieved when the prediction takes the majority vote after
giving each neighbor the chance to vote for their class attribute.
Accuracy
Now, all the KNN algorithm pieces are in place. The accuracy evaluation of
the prediction is an essential remaining concern. And evaluating the model
accuracy is an easy way, and it is called classification accuracy, which is, out
of all predictions made, the ration calculation of the total correct predictions.
Main
Then, it is time to tie them together with the primary function since we have
all the elements of the algorithm.
K – Means Clustering
As an unsupervised learning type, you can use K – means clustering in a
circumstance where data are unlabeled, i.e., data that has no defined groups
or categories. Identifying groups in data, with the variable K representing the
groups’ number, is the goal of this algorithm. Based on the features that are
provided, assigning every data point to any member of the K groups is the
iterative work of the algorithm. And also based on feature similarity, there is
a cluster of data points. Here is the K – means algorithm clustering:
1. As they also use for new data labeling, the K clusters’ centroids,
2. Training data labels (assign a particular cluster to each data point)
It becomes possible for you to analyze and find the organically formed
groups instead of defining groups before looking at the data. As you read on,
you will understand how you can determine the groups’ number. Each
cluster’s centroid defines the resulting groups as the feature values’
collection. You can interpret what kind of group each cluster represents while
the centroid features weights examination.
Clustering
The technique of data analysis that is most common exploratory that they use
for intuition acquiring about the data structure is clustering. While data points
in different clusters are quite varied such that data points in the same
subgroup, cluster, are quite the same, clustering is the task of identifying
subgroups in the data. In other words, according to a similarity measure like
correlation-based distance and Euclidean-based distance, data points in each
cluster are as similar as possible when we attempt to identify homogenous
subgroups within the data. Application-specific is the verdict of the measure
of similarity to use.
You can do clustering analysis based on the features where you attempt to
identify samples subgroups derived from elements or based on models where
we strive to identify features subgroups founded in samples. However,
feature-based clustering is what we will discuss here. In market segmentation,
clustering is what we use; in a situation where we attempt to identify the
same customers whether in the conditions of image compression or
segmentation, attributes or behaviors; document clustering based on topics,
and so on, in a circumstance where we attempt to group the same region.
Because there is no comparison of ground truth to the actual label to the
clustering algorithm output for evaluation of its performance, clustering is an
unsupervised learning method, unlike supervised learning. It is through the
process data points grouping into distinct subgroups that we have access to
investigate the structure of the data.
K – Means Algorithm
Where each data point belongs to only one group, as an interactive algorithm
and also into Kpre-defined distinct non-overlapping subgroups, clusters,
Kmeans algorithm attempts to have segregation of the dataset. Although
keeping the clusters as separate as possible, Kmeans attempts to make the
data points of inter-cluster quite comparable. The total of the squared distance
is at the minimum involving the centroid cluster and the data points when it
assigns data points to a cluster. Within the same cluster, the more
homogenous, similarity, the data points, the less variation that we have within
clusters.
For a final result generation, the K-means clustering algorithm makes use of
iterative refinement. The data set and also the clusters’ number are the inputs
of the algorithm. And for each data point, the data set is a features’ collection.
In the initial, it is with the K centroids’ approximation that the algorithms
start, which, from the data set, can either be selected or generated
indiscriminately. For the process of iteration, here are the steps used by the
algorithm:
Business Uses
For identification inside data, groups they are yet to label explicitly, they
make use of the K-means clustering algorithm. Using it confirms the
assumptions of business for unknown groups identification in complex data
sets or about the existence of groups. It will be easy to assign any new data to
the correct group when they have defined the groups and also run the
algorithm. This algorithm is so versatile that they can use it for grouping of
any type. Some of the use cases for this include:
Behavioral segmentation:
Purchase history segmentation
Activities on website, platform, or application segmentation
Interest-based personas definition
Activity-based monitoring profile creation
Inventory categorization:
Sales activity in group inventory
Manufacturing metrics in group inventory
Measurements of sorting sensor:
Motion types of sensor activity detection
Images of the group
Separate audio
Identification of health supervision groups
Anomalies and bots detection:
Bots separation from groups’ valid activity
Cleaning up outlier detection against the legitimate exercise of the
group
Also, they use it for meaningfully changed detection in data and monitors
such situation if, over time, there is a switch between groups by a tracked
data point.
Chapter 10: Neural Networks – Linear
Classifiers
Feedforward Networks
As quickly as possible, reaching the least error is the purpose we have with
using the neural net. In a loop, we pass a similar point continually because,
on all sides of a track, we are running a race. In the situation where we
initialize our weights is the starting line for the race and those parameters’
condition. Once they can produce sufficiently accurate predictions and
classifications is the finish line.
There are several steps involved in the race with those individual steps
resembling the previous steps and the subsequent one. For us to arrive at the
finish line, we will submit ourselves to the engagement in the act of
repetition, like a runner. As it learns to take notice of the most critical
features, there is an involvement of a guess with each step of a neural
network, an adjustment to the coefficient, and its weights with a minor
revision and an error measurement.
A model, whether in the state of end or beginning, is a collection of weights
since it attempts to understand the structure of the data, as well as modeling
relationship of data to labels of ground-truth, is the effort it attempts.
Ordinarily, the conclusion may be a bit bad for models even though they have
a bad beginning since its parameters get updates by the neural network; they
change over time. The close reason is that it is in ignorance that the
conception of a neural network happens. Concerning biases or weights, and
guessing correctly, it has no knowledge that will best translate the input. And
with more knowledge about its mistakes, making better sequential guesses is
what it continues to do even though it starts with a hypothesis. Through a
scientific method with a blindfold on, what you can imagine as an enactment
miniature of the scientific technique is a neural network, making more
attempts as they test hypotheses. Or more like a child; they have zero
exposure in their birth and gradually learn to provide a solution to the world’s
tribulations through their life experience exposure. As such, data becomes the
sole experience in support of neural networks.
As the simplest architecture to explain, in the course feedforward neural
network learning, what happens is what can be described in plain details. The
network experiences the presence of the input. The guesses the network make
at the end is what the map, coefficient, or a set of guesses for weights input.
Its error is the distinction between the ground truth and the guess of the
network. Contributing to the error as they measure the error with an extensive
weight adjustment, it is over its model that the network walks back the error.
For them to apply an update to the model, the neural networks’ three essential
functions’ account is the above three pseudo-mathematical formulas, loss
calculation, and scoring input. Then, they will start the step of three processes
once more. A collective feedback loop is a neural network that is set to
punish weights that result in an error and for weights that support its guesses,
reward them.
Multiple Linear Regression
Typical of any algorithm of other machine learning, simple code and math
are all about artificial neural networks, in spite of their biologically inspired
name. Indeed, in statistic, part of your learning techniques, in the beginning,
is linear regression. And it will be easy for anyone who understands how
neural network work to have a clear grasp of linear regression. Linear
regression, in a form so simple, the following is the expression of linear
regression;
Y_hat = bX + a
The input x where output estimation is Y_hat, on the vertical axis, a line
interception of a graph with two-dimension is a, and b is the slope. Let’s
concretize this: the risk of cancer risk could be Y, and the radiation exposure
could be x; your benchpress’ total weight could be Y_hat, and daily pushups
could be x; the crop’s size could be Y_hat, and the fertilizer quantity could be
x. As you can see, on the X-axis, regardless of how far along you are, there is
a proportional increase in the dependent variable Y_hat all the time there is an
addition to a unit to x. Between two variables, a starting point is a simple
relation that moves them together up or down.
For us to imagine linear regression in their multiplicity is the next step, where
several input variables produce a single output variable. Typically, one can
express it as follows:
For you to get to this point, chances are you want to know so many things
about Python, data science, machine learning, and so other related fields. You
can be the next innovator. Building innovative technology begins with an
idea, and your plan can become a reality when you make a move.
Right now, all you have to do is to imagine. Imagine how your world would
be if you can take some steps to learn more about machine learning or
perhaps neural networks. Imagine yourself a great data analyst who uses data
science to make decisions and predictions with the use of machine learning.
Imagine having all the secrets about data science lifecycle where you can
make several analyses. Imagine knowing everything about probability,
statistics, fundamental, as well as data types you’ve read in this book.
Imagine knowing all aspects of linear algebra and how you can proffer
solution to many representational problems of linear algebra.
In this book, you have read about the fundamentals of machine learning.
There are details about the prerequisites to start with machine learning and
some details about machine learning roadmap. You have the knowledge you
may need in the world of data science and Python with this book. The next
step you need to take is to go out there and conquer the world.
Finally, if you found this book useful in any way, a review on Amazon is
always appreciated!