Computer Programming Fundamentals (2024)
Computer Programming Fundamentals (2024)
FUNDAMENTALS:
4 Books in 1:
Coding For Beginners, Coding With Python,
SQL Programming For Beginners, Coding
HTML.
A Complete Guide To Become A Programmer
With A Crash Course.
Ashton Miller
© Copyright 2024 - All rights reserved.
The content contained within this book may not be reproduced, duplicated
or transmitted without direct written permission from the author or the
publisher.
Under no circumstances will any blame or legal responsibility be held
against the publisher, or author, for any damages, reparation, or monetary
loss due to the information contained within this book. Either directly or
indirectly.
Legal Notice: This book is copyright protected. This book is only for
personal use. You cannot amend, distribute, sell, use, quote or paraphrase
any part, or the content within this book, without the consent of the author
or publisher.
Disclaimer Notice: Please note the information contained within this
document is for educational and entertainment purposes only. All effort has
been executed to present accurate, up to date, and reliable, complete
information. No warranties of any kind are declared or implied. Readers
acknowledge that the author is not engaging in the rendering of legal,
financial, medical or professional advice. The content within this book has
been derived from various sources. Please consult a licensed professional
before attempting any techniques outlined in this book.
By reading this document, the reader agrees that under no circumstances is
the author responsible for any losses, direct or indirect, which are incurred
as a result of the use of information contained within this document,
including, but not limited to, — errors, omissions, or inaccuracies.
Eugene Gates
Introduction
Tool support
You should always consider working with a programming language that has
all the tools you need to build your project effortlessly. This way, you will
not just manage to build the application, but you can also maintain it
without a hitch.
Library support
Before you settle on a given language, make sure you consider the library
constraints. Ensure that the library available will not just meet your needs,
but will also solve other needs arising down the line.
Elasticity
Flexibility is one of the key features you must look at. For your projects,
ensure you use a language that allows you to scale the application
accordingly over time. This means you should manage to add or remove
some features and programs into the application without affecting the
performance.
Platform choice
Always think about the platform upon which the application will run. While
most languages support different platforms, their suitability might not be
pleasant across the board. Take programs written in C, for example. These
programs are best suited for Linux and Windows-based systems. While you
might experiment with other platforms, the performance might not be as
you would experience in a Windows or Linux environment.
Programming languages
If you are a beginner in web programming or software development, you
might have come across so many languages to the point where you are
unsure where to start. A lot of people have been there. There are so many
languages to choose from. However, you need to know where to begin, and
how to build on what you have learned. Here are some of the top
programming languages in use today.
Python
Python stands out today as one of the most versatile programming
languages in the world. When using Python, you can write code and at the
same time run it without using a compiler. Python further boasts support for
code readability. What this means is that its syntax structure allows you to
write a few lines of code to make a point. This is also possible in C++ and
Java. The interesting thing about Python is that while it is an advanced
language, it is very easy, and beginner programmers can pick up on it very
fast.
There are so many popular applications currently running on Python,
including Google, Yahoo, Pinterest and Instagram. Most of these are
websites and applications that are heavy on memory usage, which means
that Python is not just perfect for automated memory management, it also
features a very big library and supports various paradigms in development.
CSS
Cascading Style Sheets, CSS, is a markup language. It defines the way a
website or web page appears, when coupled with HTML. Some of the
elements that make up CSS determine things like the font style and size,
colors and any other design features of the website.
CSS helps developers create visually pleasing websites. It has also come in
handy in the development of appealing mobile applications too. CSS
features a language syntax that is almost similar to XHTML and HTML. As
a result, the language syntaxes can work together without a hitch.
Java
Java is one of the most in-demand languages today. It is widely used in
developing mobile apps and games. It is object-oriented, and is favored by
most developers because it can be used across different platforms.
Therefore, a program written on a Windows-based machine can still run on
a Mac OS device.
JavaScript
JavaScript is currently one of the best programing languages you need to
learn. It empowers you to manage the browser, allow front-end scripts to
run, edit and display content on the website and so forth. JavaScript allows
for asynchronous interaction between users and the application.
JavaScript is one of the most popular languages given its prevalence in
game development and building desktop applications. All the major
browsers support JavaScript, so you do not need plug-ins or a compiler to
run an application.
JavaScript is a functional language. Objects in JavaScript are first-class,
associating with their characteristics and functions. An example is a nested
function, which is a function inside a function.
This is also one of the most dynamic languages because types are related to
values, not variables. As a result, you can test project types in several ways.
JavaScript is an object-oriented language, and as such all the objects within
its environment are associative arrays.
PHP
Hypertext Processor, PHP, is a server-side language which is recommended
for use in web development and other regular programming needs. PHP has
been around since 2004, but currently powers hundreds of millions of
websites all over the world.
Given that PHP is an interpreted script language, it is ideal for back-end
programming because of the need for an interpreter. It is suitable for this
type of programming because you can run server services in the background
while still developing the application or website.
Ruby
Ruby is a dynamic programming language that has been around since 1993.
Ruby is ideal for building websites and mobile applications. As a highly
scalable language, it provides an astute balance between functional
programming and imperative programming.
Ruby is not just easy to understand, it is also one of the easiest languages to
write. However, for beginner developers who are just getting into Ruby, it is
wise to start with Ruby on Rails. Ruby on Rails makes it easier for you to
work with Ruby, and enjoy the experience.
Ruby is often recommended for websites or web servers that encounter lots
of traffic. Some popular examples include Twitter and Hulu.
SQL
Structured Query Language, commonly identified in its abbreviated form
SQL is a programming language that was specifically written for database
operations. Data manipulation, storage and retrieval are some of the key
features in SQL. A lot of web based frameworks run SQL today, given that
it is effective in maintaining database integrity, is secure and maintains data
precision.
C
C is similar to C++. It is a general purpose language that is often used to
build supporting elements for other languages like Java, C++ and Python.
This means that most of the supported languages borrow some features
from C, such as standard libraries, syntax and control structures. This
explains why it is always advisable that you learn C++ and C before you
expand your knowledge to other languages, so that you have a firm
foundation in the basics.
C-Sharp (C#)
Microsoft developed C# in 2000 as an object-oriented programming
language. It is popular in desktop applications, and became an integral part
of applications built for Windows 8 and Windows 10. To run C# therefore,
you must have the .NET framework installed on your computer. C# was
built to compete with Java.
Compared with C++, C# has logical and consistent code, which is one of
the reasons why it is one of the best languages for beginners to grasp. C# is
a statically typed language, which means that you can check your code
before you run it into applications. Therefore, it is easier to identify errors
when programming in C#.
C++
C++ is a case-sensitive programming language. It is general purpose, and
presents programmers with the necessary tools for memory manipulation at
a low level. C++ is an interesting language because it combines the features
of high-level languages and low-level languages. As a result, it is often
construed as a mid-level language.
Primarily, C++ is an object-oriented language, thanks to the following
inherent features:
Data hiding
Inheritance
Encapsulation
Polymorphism
C++ is a superset of C, so they share a lot of similarities. This also means
that if you write a program in C, it is also a C++ program. C++ is a very
detailed language. For beginners, it is advisable that you focus on the
concepts instead of the details, lest you get confused.
So, where does this leave you? The best place for you to start depends on
what you want to pursue in your career. If you feel database management is
right for you, you should start with C++ or C to become an SQL developer.
Back-end developers will find JavaScript, PHP, Python, C#, Ruby and
Python handy, while front-end developers should be okay with JavaScript.
If you plan to delve into game development, focus on C# and C++. Mobile
app developers should emphasize Java, Swift and C#. Programmers who
are interested in building desktop applications should focus on Python, C++
and Java.
Remember that this is one of the most dynamic industries. Therefore,
expect new releases and updates from time to time. It is difficult to advise
anyone which programming language is best because choices depend on
needs assessment.
Chapter 2: Getting Started With Coding
Think about why you wanted to learn to code in the first place. For a lot of
people, it is because they want to make something that just doesn’t exist
yet. Others may want to do it because they know software developers are
companies alike. Identify what drives you and then start looking for sources
of inspiration that encourage you to stay focused on your goals. For a coder,
you towards the right tools. Like if you want to get involved with artificial
and has a lot of flexibility. If you're going to build the next Candy Crush
addiction, you will need to focus on mobile apps and learn Swift,
A pair of 1080p displays will make a world of difference even if you are a
beginner programmer. It is much better than those ultrawide displays that
spreadsheet fanatics love. You do not need an ultrawide display since
coders generally need more vertical screen real estate. But with a two
displays and set in “extended desktop” mode, you can have a full screen
dedicated to your coding environment and another screen for another
coding environment if you like doing multiple projects or managing
different codes or you can open up your browser for research or your
flowchart or anything you just want to drag there at your leisure.
Next up is the keyboard and this is going to surprise you if you’ve been
stuck with the same $10-$20 keyboard for the past several years. You might
even be pretty comfortable mashing away at 60-70 words per minute and
not thinking about “fixing what isn’t broken”. Try a mechanical keyboard
as soon as you have the budget.
IDEs
Once you are ready to move on beyond HTML, Python should be your next
stop as it is one of the most accessible modern programming languages to
learn. To quickly get started, consider trying PyCharm which is an IDE that
even the pros use. The smart assistance feature helps with the debugging
while the extensive documentation can walk you through the different
features so you can run and test web apps. JavaScript, TypeScript,
CoffeeScript, HTML, CSS and other technologies are supported by this
IDE. If you want to expand beyond HTML and CSS and dive into
JavaScript, Java and PHP, install Apache NetBeans IDE. Google even has
its own IDE called Android Studio serving as the primary IDE for
developing Android mobile apps with Kotlin as the primary language.
Chapter 3: Functions
later referenced that file whenever we wanted to repeat the same exact
commands?
Well, we basically used what we’ll call from now on, “functions”. A
function is effectively a block of statements that takes in inputs from other
parts in the program, processes (or doesn’t, in some cases) these inputs, and
gives results.
So, an entire program can contain multiple functions and these functions
can be invoked multiple times depending on what use we have for them.
Why do we need functions though?
Well, primarily because we will need them sometimes. We will be dealing
with really complex problems where we will end up using functions in
order to write reusable code. Sometimes, problems are so big that we have
to break our approach to solving them into steps and we can model each
such step using a function. It is a very effective way of organizing both
code and our thoughts.
Quick question - what function have you already seen in C++? The main
function! It is a particular type of function that defines all the code that will
run.
Let’s see how we can define a function and run a function in C++:
#include<iostream>
using namespace std;
int sum(int a, int b) {
int returnSum = a + b;
return returnSum;
}
int main() {
int numOne = 10;
int numTwo = 20;
int sumValue = sum(numOne, numTwo);
//sumValue will have the value 30
cout << sumValue;
}
The above program creates and uses a function called sum, to compute the
amount of two numbers and return the result. Usually, you wouldn’t make
functions for
such trivial applications but we’re looking at the above program to learn
about functions.
Let’s look at the function call first -
int sumValue = sum(numOne, numTwo);
The above statement calls the function by passing in the variables numOne
and numTwo to be processed by the sum function (definition is mentioned
above the main function) and the result of the computation done by the
function is then assigned to the variable sumValue.
Let’s look at the function definition:
int sum(int a, int b) {
int returnSum = a + b;
return returnSum;
}
The variables in the parentheses (a and b) specify the datatype and labels
for the variables that will be sent to the function. Once returnSum is
computed, we use the “return” keyword to specify that we want this value
to be sent to back to wherever the function is being called once the
necessary computation/processing/work is done. Note that the variables a
and b hold the values that are sent to the function. Also, the reason the value
of the variable
returnSum will be accessible outside the function is that its value is being
sent out of the function. If you created any other variable for any other
purposes inside the function it wouldn’t be accessible outside the function.
In other words, it’s “scope” is limited to the function in which it is defined.
The function itself has a datatype. This data type specifies the data type of
the value being returned. So, if your function returns a string its value is
eventually being stored in a variable with a double datatype, C++ would
raise an error. It would first try to make sense of your mistake and try to
convert the string to a double but because such a conversion is not possible,
it would then raise an error.
Let’s look at another example of a function -
#include<iostream>
using namespace std;
void functionExample() {
cout << "This function does nothing!" << endl;
}
int main() {
functionExample();
}
In the above function, we’ve defined a function called functionExample.
Pay attention to the syntax. The function’s data type is “void” which is a
keyword that indicates that the function does not return a result to from
where it was called.
The statements within the curly braces following the function name specify
what the function does. In order to utilize the function, you will have to use
it in other functions by specifying its name and passing variables. For
example, in the above program, the function is called from the primary
function by the command
“functionExample();”.
Pass By Value and Pass By Reference:
Remember how we passed variables to our functions? That’s a widespread
thing to do in any language that you will come across. However, C++ has a
unique feature when it comes to this particular process.
Let’s look at what this is through an example -
#include<iostream>
#include<string>
using namespace std;
void addTwo(int input) {
input = input + 2;
}
int main() {
int a = 10;
addTwo(a);
cout << a << endl;
}
The program above adds 2 to whatever the input value is. One would
usually expect that the output of the program would be a 12. But, it is
actually a 10. This is because even though the value 10 and the variable a is
passed to the function addTwo, it’s value is copied to the input variable in
addTwo. As a result, C++
treats the variables a and input as two separate entities even though they
share the same value. The variable input effectively copies the value of the
variable a.
Pass By Reference:
In order to modify this behavior, we’ll make use of the ampersand operator
(&) just before mentioning the label for the inputVariable. This would make
C++ look
at the inputVariable’s label as an alias for the variable that’s being passed in.
Any modifications made to this “alias” would now also affect the variable
whose value was passed in. This way of passing a variable to a function is
termed as passing by reference. Let’s modify the function we just worked
with -
#include<iostream>
#include<string>
using namespace std;
void addTwo(int& input) {
input = input + 2;
}
int main() {
int a = 10;
addTwo(a);
cout << a << endl;
}
The output would be 12.
Example - Write a program that reverses any string that the user provides.
#include<iostream>
#include<string>
using namespace std;
string reverseString(string input) {
string reverse = "";
for (int counter = input.size() - 1;counter >= 0;counter--) {
reverse = reverse + input[counter];
}
return reverse;
}
int main() {
string str;
cout << "Enter a string: ";
cin >> str;
string reversedString = reverseString(str);
cout << "Reversed String: "<<reversedString<<endl; cout << "Original
String: " << str << endl;
}
Example Output:
Enter a string: Library
Reversed String: yrarbiL
Original String: Library
Press any key to continue . . .
The above program takes in a string and passes it to the reverseString
function which traverses the string from the last letter and adds it to an
empty string until it reaches the index 0. The function then returns this
newly formed string. Since we are passing by value the value of the original
string (str) does not change.
Containers are precisely what their name conveys. They hold data in forms
that are easily accessible for us. We will look at arrays and vectors.
Arrays:
Arrays are containers that hold data of a particular data type and are fixed in
size. That is, once you initialize an array with a specific size you can’t
increase its size unless you create another variety of a larger size and copy
over all the elements. Arrays also hold data in a linear sequence and
preserve “order”. Once data is put inside an array, it stays in the exact place
you put it in unless you make changes to the variety.
Arrays are also not for beginner coders but when used properly, you can
make far more efficient programs. If you find yourself making too many
variables to store similar data, you can simplify things by creating an array
that can store these values in their own dedicated cells. Think about the way
apartments and condos work. Each room doesn’t have its private mailbox.
Instead, there is a dedicated room in the apartment containing a large
mailbox with individual compartments each with their own locks to
represent each room.
Let’s learn how to create an array through an example:
#include<iostream>
using namespace std;
int main() {
int arrayOfNumbers[5] = { 10,23,45,67,12 };
}
The above example shows how to create an array. The array is defined by
the label “arrayOfNumbers”. The number within the square braces - 5 in
this case establishes the number of elements the array holds. The “int”
specifies that the array will contain only integers. This datatype can be
changed depending on what type of array you want to create. Finally, the
numbers within the curly braces represent the data that the array holds.
When you initialize an array with its values, you specify the values between
the curly braces.
To access a number, say 23, within the array, we do so by specifying an
“index”
as follows -
cout<<arrayOfNumbers[1];
The above statement will print the number 23 on to the screen. Now you
may notice I used the number 1 as my index and not 2. That’s because C++
follows zero-based numbering where the first number in a collection starts
at the index 0. So, in order to access the first number in arrayOfNumbers,
you would use the 0 index like -
cout<<arrayOfNumbers[0];
Instead of initializing the array at the very moment you declare it, you can
create it and later assign individual values to each position by indexing it.
By the same logic, you can modify the values in the array as well.
So, you can do things like -
arrayOfNumbers[1] = arrayOfNumbers[1] + arrayOfNumbers[2] - 5; Now,
arrayOfNumbers[1] would equal 63.
Everything looks fine and dandy until now doesn’t it? Well, what would
you do if your array had 200 elements and you had to go through each
component and add 5 to it? You can’t do something like arrayOfNumbers +
5, because arrayOfNumbers is a “container” that holds numbers. It points to
a memory space in your computer that contains the numbers in the array.
So, adding 5 to arrayOfNumbers doesn’t make sense and will actually
throw an error.
Chapter 5: Strings
string. In other words strings are array but of character datatype. An array
we can also specify conditions which when are or are not satisfied with the
There are three types of loops we’re going to look at - for, while, do while
Let’s look at the for loop first -
The for loop is mostly used for executing a set of statements a set number
of times. It’s also used to iterate through extensive collections and do
something to each element.
Let’s look at an example and then see what for loop is all about.
#include<iostream>
using namespace std;
int main() {
for (int i = 0; i < 10; i++) {
cout << "hello" << endl;
}
}
The output is -
hello
hello
hello
hello
hello
hello
hello
hello
hello
hello
Press any key to continue . . .
The program above basically printed hello ten times. Basically, the for loop
that we just defined ran the statement below it 10 times and so “hello” was
published ten times.
But why correctly did it run 10 times?
We’ll know once we understand the structure of the for loop.
The for loop consists of three parts - initialization, logical comparison, and
the increment or decrement statement.
Initialization (int i=0):
In the for loop, the variable i is initialized to the value 0. The variable i
works as a counter and at the start of the circle, before any statements are
executed, the amount of this variable is 0. That is what initialization means.
Also, notice how I didn’t have to define the variable outside the loop and
then equate it to 0 within the loop (although I can do that as well). The fact
that I declared it within the loop means that the variable i will not be
accessible outside the loop. However, if I declared it outside the loop and
assigned to it an initial value inside the loop, I would still be able to access
the variable outside the loop.
Logical Comparison (i<10):
The logical comparison defines the condition that needs to be satisfied for
the loop to keep executing the statements inside it. This condition is
checked every single time the loop is run including the very first iteration.
In our example, we check if the variable i is less than 10. If that is true the
loop runs, otherwise, the loop is broken.
Increment (or Decrement) (i++):
Every time the loop finishes running, the increment or decrement part is
executed. In our example, the value of i increases after every iteration of the
loop. But this is also within our control. We could depending on our
purposes, decrement the variable we defined or increase it by multiplying it
by itself, etc.
How it all works together:
The loop counter is initialized, the condition is checked and if the condition
holds, the statement(s) below is/are executed. Then the increment or
decrement part is reached and the logical comparison part is rerun. If the
condition holds, the loop runs again, if not, it breaks.
The for loop can be used in different ways apart from just as a tool to do
something multiple times. We can use it to access elements in our array.
Here’s how we can do that -
#include<iostream>
using namespace std;
int main() {
const int arraySize = 10;
int arrayValues[arraySize] = { 1,2,3,4,5,6,7,8,9,10 }; for (int counter = 0;
counter < arraySize; counter++) {
cout << arrayValues[counter] << endl;
}
}
In the code above, we’ve first declared the arraySize as 10 and as a
constant.
And then we’ve initialized our array with the numbers from 1-10. Now,
instead of individually accessing each element separately, we’ve used a for
loop to do the work for us.
Since the variable counter initially equals 0 and it grows one step at a time
and stops at 9, we can use counter’s value to index the array’s elements at
each position.
So, the output would look something like this -
1
2
3
4
5
6
7
8
9
10
Press any key to continue . . .
Another way to loop is with while loops. Let’s explore with an example:
#include<iostream>
using namespace std;
int main() {
int arrayValues[5] = { 5,6,7,8,9 };
int counter = 0;
while (counter < 5) {
cout << arrayValues[counter] << endl; counter++;
}
}
The while loop executes the statements inside it 5 times in the example. The
counter variable is initialized outside the loop and is incremented once all
the statements in the loop are specified. If you forget to update the counter,
the while loop will run forever!
A slight modification of the while loop above is the do-while loop. The do
while loop is exactly like the while loop, except that it runs the statements
inside at least once, irrespective of the condition.
Let’s look at an example based off of the while loops -
#include<iostream>
using namespace std;
int main() {
int arrayValues[5] = { 5, 6, 7, 8, 9 }; int counter = 0;
do {
cout << arrayValues[counter] << endl; counter++;
} while (counter < 5);
}
In the above program, the statements within the “do” block are run at least
once irrespective of the comparison being made. Subsequent iterations are
however made on whether the condition is met.
Now that we know quite a bit about loops, let’s move back to arrays.
Remember how I said that arrays in C++ are fixed in size? Well, that can’t
be changed. However, C++ has a built-in container called a vector. A vector
is built on top of an array and doesn’t have a fixed size. It can be added to
as long as you want to.
To use vectors, you have to include the vector library.
As always, let’s learn through an example --
#include<iostream>
#include<vector>
using namespace std;
int main() {
vector< int> vec = { 1, 2, 3, 4, 5, 6 }; cout << vec[0] << endl;
vec.push_back(7);
cout << vec[vec.size() - 1] << endl;
}
So, you can see that we’re using the vector library. And we’re initializing
the vector “vec” just like we initialized an array. However, there are a
couple of differences. The first one is that we’re specifying the data type of
the vector within angular brackets after the keyword “vector”. This data
type basically defines the datatype of all the elements within the vector.
Notice how indexing with vectors is just like indexing with arrays.
“vec.push_back(7)” adds the number 7 to vector. So, the vector now
contains 1,2,3,4,5,6,7. The “.push_back(7)” notation may be new to you. It
basically makes use of the “push_back” method to add a value to the vector.
The “.” basically specifies that this method applies to the vector you
created. We’ll look at methods in detail when we talk about Object Oriented
Programming.
Just as you added integers to the vector, you can also “pop” integers from
the end of the vector. For that you will use the pop_back method -
vec.pop_back().
Doing so will remove the last element from the array.
Here is a list of some commonly used vector methods: Method
Purpose
push_back(<value>)
Add’s <value> to the end of the vector
pop_back()
Remove the last element from the
vector
insert(<position>,<value>)
Adds <value> to the vector at the
index specified by <index>
clear()
Clears the entire vector
Sample Output:
How many students are in your class? 5
Enter the score for student #1 : 75
Enter the score for student #2 : 70
Enter the score for student #3 : 80
Enter the score for student #4 : 92.75
Enter the score for student #5 : 93.50
The first for loop takes in the score for each student and puts the score in a
vector. This vector is later accessed and all the scores are added to compute
the net score of the class. The average is then calculated by dividing this
sum by the number of students in the class.
Example - Build a calculator program that calculates the sum, the product,
and the difference between the two numbers and keep doing this until the
user enters the string ‘STOP’. This program has to run at least once.
#include<iostream>
#include<vector>
#include<string>
using namespace std; int main() {
string stopString;
do {
cout << "Enter the first number: "; double firstNumber;
cin >> firstNumber;
cout << endl << "Enter the second number: "; double secondNumber;
cin >> secondNumber;
cout << endl << "Sum: " << firstNumber + secondNumber << endl; cout <<
"Product: " << firstNumber*secondNumber << endl; cout << "Difference: "
<< firstNumber - secondNumber << endl; cout << "Enter STOP if you want
to stop otherwise enter any other string";
cin >> stopString;
} while (stopString != "STOP");
}
Here’s a sample output -
Enter the first number: 1
Enter the second number: 2
Sum: 3
Product: 2
Difference: -1
Enter STOP if you want to stop otherwise enter any other string continue
Enter the first number: 5
Enter the second number: 7
Sum: 12
Product: 35
Difference: -2
Enter STOP if you want to stop otherwise enter any other stringSTOP
Press any key to continue . . .
Chapter 7: Modules
program used.
Import Statement
This statement is used to import a module.
Through any Python code file, its process is as follows:
The Python interpreter searches the file system for the
current directory where it is executed.
Then, the interpreter searches for its predefined paths in its
configuration.
When it meets the first match (the name of the module), the
interpreter automatically executes it from start to finish.
When importing a module for the first time, Python will generate a
compiled .pyc extension file.
This extension file will be used in the following imports of this module.
When the interpreter detects that the module has already been modified
since the last time it was generated, it will create a new module.
Example:
This will print:
You must save the imported file in the same directory where Python is using
the import statement so that Python can find it.
As we could see in our example, importing a module allows us to improve
the functionalities of our program through external files.
Now, let's see some examples. The first one is a calculator where will create
a module that performs all the mathematical functions and another program
that runs the calculator itself.
The first thing we do is the module "calculator.py" that is responsible for
doing all the necessary operations.
Among them are the addition, subtraction, division, and multiplication, as
you can see.
We included the use of conditional statements such as if, else, and elif.
We also included the use of exceptions so that the program will not get
stuck every time the user enters an erroneous value at the numbers of the
calculator for the division.
After that, we will create a program that will have to import the module to
so that it manages to do all the pertinent mathematical functions.
At this time, you might be thinking that the only existing modules are the
ones that the programmer creates.
The answer is no since Python has modules that come integrated to it.
With them, we will make two more programs: the first one is an
improvement of the one that we have just done, and the second one will be
an alarm that will print on screen a string periodically.
First example:
The first thing that was done was to create the module, but at first sight, we
have a surprise, which is that math was imported.
What does that mean to us?
Well, that we are acquiring the properties of the math module that comes by
default in Python.
We see that the calculator function is created that has several options.
If the op value is equal to 1, the addition operation is made.
If it is equal to 2, the subtraction operation is made, and so on.
But so new is from op is equal to 5 because, if this is affirmative, then it
will return the value of the square root of the values num1 and num2
through the use of math.sqrt(num1), which returns the result of the root.
Then, if op is equal to 6, using functions "math.radians()" which means that
num1 or num2 will become radians since that is the type of value accepted
by the functions "math.sin()", meaning that the value of the sin of num1 and
num2 will return to us, which will be numbers entered by users arbitrarily
who will become radians and then the value of the corresponding sin.
The final thing will be to create the main program, as it can be seen next:
Here, we can see the simple program, since it only imports the module
"calculator.py", then the variables num1 and num2 are assigned the value
by using an input.
Finally, an operation to do is chosen and to finish is called the calculator
function of the calculator module to which we will pass three parameters.
Second example:
We are going to create a module, which has within itself a function that acts
as a chronometer in such a way that it returns true in case time ends.
In this module, as you can see, another module is imported, which is called
as "time", and as its name refers, functions to operate with times, and has a
wide range of functions, from returning dates and times to help to create
chronometers, among others.
First, create the cron() function, which starts declaring that the start Alarm
variables will be equal to time.time, which means that we are giving an
initial value to this function o know the exact moment in which the function
was initialized to then enter into an infinite cycle.
Since the restriction is always True, therefore, this cycle will never end,
unless the break command is inside it.
Then, within the while cycle, there are several instructions.
The first is that the final variable is equal to time.time() to take into account
the specific moment we are located and, therefore to monitor time.
After that, another variable is created called times, and this acquires the
value of the final minus start Alarm.
But you will be wondering what the round function does.
It rounds up the values; we do that to work easier.
But this is not enough, therefore, we use an if since, if the subtraction
between the end and the beginning is greater or equal to 60, then one
minute was completed, and what happens to this?
Why 60?
This is because the time module works with a second and for a minute to
elapse, 60 seconds have to be elapsed, therefore, the subtraction between
the end and the beginning has to be greater than or equal to 60, in the
affirmative case, True will be returned and finally, we will get out of the
infinite cycle.
Once the alarm module is finished, we proceed to make the program, as we
can see below:
We can see that the program imports two modules, the one we have created,
the alarm and the time module.
The first thing we do is to create the variable s as an input which tells the
user if he wants to start.
If the answer is affirmative, then the variable h representing the time will be
equal to "time.strftime ("%H:%M:%S")", which means that we are using a
function of the time module that returns the hour to use in the specified
format so that it can then be printed using the print function.
The next action is to use the alarm module using the command
alarm.cron(), which means that the cron() function is being called.
When this function is finished, the time will be assigned to the variable h,
again, to end printing it and being able to observe its correct operation.
We can say that the modules are fundamental for the proper performance of
the programmer since they allow to make the code more legible, in
addition, that it enables subdividing the problems to attack them from one
to one and thus to carry out the tasks efficiently.
Locate a Module
When importing a module, the interpreter automatically searches the same
module for its current address, if this is not available, Python (or its
interpreter) will perform a search on the PYTHONPATH environment
variable that is nothing more than a list containing directory names with the
same syntax as the environment variable.
If, in any particular case, these previous actions failed, Python would look
for a default UNIX path (located in /user/local/lib/python on Windows).
The modules are searched in the directory list given by the variable
sys.path.
This variable contains the current directory, the PYTHONPATH directory,
and the entire directory that comes by default in the installation.
Syntax of PYTHONPATH
A PYTHONPATH syntax made in windows looks like this:
Unlike a PYTHONPATH syntax made in UNIX
Chapter 8: Files
Note that the last two options require the access mode to have binary
access.
If the access mode does not have binary access, the last two options will be
useful to determine the current position of the pointer [seek(0, 1)] and the
position at the end of the file [seek(0, 2)].
For example:
>>> file1 = open("sampleFile.txt")
>>> file1.tell()
0
>>> file1.seek(1)
1
>>> file1.seek(0, 1)
0
>>> file1.seek(0, 2)
11
>>> _
File Access Modes
To write to a file, you will need to know more about file access modes in
Python.
There are three types of file operations: reading, writing, and appending.
Reading allows you to access and copy any part of the file’s content.
Writing allows you to overwrite a file’s contents and create a new one.
Appending allows you to write on the file while keeping the other content
intact.
There are two types of file access modes: string and binary.
String access allows you to access a file’s content as if you are opening a
text file.
Binary access allows you to access a file on its rawest form: binary.
In your sample file, accessing it using string access allows you to read the
line “Hello World”.
Accessing the file using binary access will let you read “Hello World” in
binary, which will be b'Hello World'.
For example:
>>> x = open("sampleFile.txt", "rb")
>>> x.read()
b'Hello World'
>>> _
String access is useful for editing text files.
Binary access is useful for anything else, like pictures, compressed files,
and executables.
There are multiple values that you can enter in the file access mode
parameter of the open() function.
But you do not need to memorize the combination.
You just need to know the letter combinations.
Each letter and symbol stands for an access mode and operation.
For example:
r = read-only—file pointer placed at the beginning
r+ = read and write
a = append—file pointer placed at the end
a+ = read and append
w = overwrite/create—file pointer set to 0 since you create
the file
w+ = read and overwrite/create
b = binary
Writing to a File
When writing to a file, you must always remember that Python overwrites
and not insert file.
For example:
>>> x = open("sampleFile.txt", "r+")
>>> x.read()
'Hello World'
>>> x.tell(0)
0
>>> x.write("text")
4
>>> x.tell()
4
>>> x.read()
'o World'
>>> x.seek(0)
0
>>> x.read()
'texto World'
>>> _
You might have expected that the resulting text will be “textHello World”.
The write method of the file object replaces each character one by one,
starting from the current position of the pointer.
Practice Exercise
For practice, you need to perform the following tasks:
Create a new file named test.txt.
Write the entire practice exercise instructions on the file.
Close the file and reopen it.
Read the file and set the cursor back to 0.
Close the file and open it using append access mode.
Add a rewritten version of these instructions at the end of the
file.
Create a new file and put similar content to it by copying the
contents of the test.txt file.
Chapter 9: Programming Paradigms
was multi-paradigm or not. What this usually means is that with multi-
paradigm languages you can code your applications following these three
different "styles", even though there are more than just these three. The
paradigms are:
Procedural Programming
Object-Oriented Programming (OOP)
Functional Programming
Just like the programming languages themselves, these paradigms came
about with the idea to solve specific problems, and then, because we're all
lazy monkeys, we ended up forcing them to solve all problems. There is
nothing bad about any of them, although you may not believe this from
hearing me speak about them. Programming suffers from most of the same
issues regular writing does and we can boil them all down to one word:
clarity. How to code without repeating yourself? How to organize your code
so that you don't end up adding to your workload? How to make sure other
people can understand your code? How to make sure you can get back to
your code months from now and still understand it? These are all worthy
concerns in programming and each paradigm will try to address these
problems in their own way.
I chose to introduce the paradigms with the old and tried method of coding
the same thing in the three different styles. For this, I decided the game of
Cluedo (or Clue depending on where on the globe you grew up in). Not
unlike the way we coded the magic tricks, we'll transform a typical game of
Cluedo into code. I suspect the choice for this came from the fact that
procedural is a word often used to describe a type of murder mystery and
because OOP has the idea of "inheritance" as one of its unique concepts and
the word put me in mind of rich aunts being murdered for the sake of their
millions. I fear my mind thinks in puns.
Be aware that with the exception of the first paradigm, it will feel like
you're learning to program all over again. Relax. It's not true. Remember
that programming is just a bunch of simple operations (store, add, multiply,
compare...) built around strings, numbers, and booleans and abstracted to
readable syntax and structures (collections, loops, if statements, and
functions). Try to focus on these building blocks first and then take notice
of the curious ways things are accomplished through each paradigm. We'll
be adding new ways to add context to our code, new kinds of code blocks
with their own peculiar rules, and a whole bunch of new syntax and
abstractions, but at the heart of it, we're still talking about the same thing.
The paradigms also bleed into each other, the lines between them is quite
blurred, and when I introduce a concept connected to one of them I do not
mean that concept is not applicable to the others (remember, the languages
I've shown you here are all multi-paradigm). You can code procedurally
with a slight bent towards objects. You can code objects with a tendency
towards functional ideas, and with some functional languages, you can use
objects in your logic.
Chapter 10: Object-Oriented Programming
Before proceeding, I want you to think about what an object is. Yes,
objects that you come across every day. What’s common to all objects? The
fact that a lot of them have specific characteristics and functions. A pen can
have a color and can be used to write. So in the case of a pen, its color is
write with it. Now, this same framework applies to living things too. A dog
In C++, we can model such objects and work with them. Object-Oriented
Programming is basically building a program around objects! Each object
has attributes (the characteristics) and methods (the functions/utility). Now
in order to create an object, we have to give C++ a blueprint on how to
create this specific object that we’re trying to make. This blueprint is
termed a class. All objects are created from a class and come with a set of
attributes and functions that we can use.
Now, a valid question is why? Why do we even need Object Oriented
Programming?
The most significant benefit is that it lets us reuse code whenever and
wherever we want.
Once I create an object, I can use it wherever I want. And once a class is
designed (correctly, without any errors) every purpose that the class
produces is free of errors and can be used reliably, therefore, allowing us to
create more bug-free code. We don’t have to know how an object works
once we create it and use it.
We just need to know how to use it. This becomes an advantage when we
work with extended programs.
So to recap - An object has functions (we will call these “methods”) and
attributes (we will call these “instance variables”). There are other types of
variables called “static variables” or “class variables”.
Objects are created from classes which basically act as blueprints.
#include<iostream>
using namespace std;
class EmptyClass {
};
int main() {
EmptyClass emptyClassObject;
}
The above program creates an empty class and instantiates an object.
class EmptyClass {
};
The above stub of code represents the class that we created. Notice how
we’ve used the keyword “class” to specify that we’re creating a class.
“EmptyClass” is the name of the class we’ve created. We can change this
depending upon the name we wish to give our class. All the instance
variables and methods will go within the brackets, but since we created an
empty class we don’t have any class members.
In the primary function, we’ve instantiated an object.
EmptyClass emptyClassObject;
emptyClassObject in the above stub is an object that’s created using the
EmptyClass class and thus holds all the properties that the class defines. But
because we haven’t set any properties within EmptyClass, its object is
practically useless.
But before we start adding stuff to the class we have to understand what
access modifiers are. Now, one of the features of object-oriented
programming is that it is able to abstract details of the class from parts of
the program outside the class.
This is also known as data hiding. The way we enforce this in C++ is
through access modifiers. There are three access modifiers in C++ - private,
public, and protected. We’re going to look at private and public.
When we use the private access modifier while defining a variable or a
method we’re basically saying that these members of the class cannot be
accessed outside of the class, even by their own objects! These members
can only be accessed by methods within the class. If you don’t want any
part of the code to access certain variables or methods, make them private!
When we use the public access modifier while defining class members,
we’re saying that they can be accessed from “everywhere”. They can be
accessed from outside the class using an object of the class.
Example:
#include<iostream>
using namespace std;
class ExampleClass {
private:
int privateVariableOne;
public:
int publicVariableOne;
void initializePrivateVariableOne(int value) {
privateVariableOne = value;
}
int incrementPrivateVariableOne() {
privateVariableOne++;
return privateVariableOne;
}
};
int main() {
ExampleClass object;
object.publicVariableOne = 10;
//Error - object.privateVariableOne = 10;
object.initializePrivateVariableOne(20);
//OK! Now, privateVariableOne = 20
object.incrementPrivateVariableOne();
//OK! Now, privateVariableOne = 21
}
In ExampleClass, all variables and methods declared under the modifier
“private:” are not accessible outside the class. The opposite is true for
members declared under the “public:” label which can be accessed outside
the class through objects (also called “instances”) of the ExampleClass
class.
The primary function shows how an instance is created. Akin to how the
data type is used while declaring a variable, the name of the class is used
while creating an example of the class.
ExampleClass object;
In the above line of code, “object” is an instance of ExampleClass and can
access everything that is declared as public within the class. This access is
allowed for by using the dot operator (“.”).
object.publicVariableOne lets us access the publicVariableOne that is tied to
the instance. Keep in mind that if we create another example of this class,
we’ll get access to a completely separate and a brand new example which
won’t reflect changes made to the first instance that we created - “object” in
this case.
Now, there are times when we want to instantiate an object with a set of
predefined values. We can do using a constructor, which is declared within
the class definition. It has no datatype, and its name is the name of the class
followed by brackets that may or may not take in parameters (depending on
how you wish to create this class).
Let’s add a constructor to ExampleClass:
#include<iostream>
using namespace std;
class ExampleClass {
private:
int privateVariableOne;
public:
ExampleClass(int publicVariableValue) {
//This is the constructor
publicVariableOne = publicVariableValue;
}
int publicVariableOne;
void initializePrivateVariableOne(int value) {
privateVariableOne = value;
}
int incrementPrivateVariableOne() {
privateVariableOne++;
return privateVariableOne;
}
};
int main() {
ExampleClass object(30);
//object.publicVariableOne is now 30.
object.publicVariableOne = 10;
//Error - object.privateVariableOne = 10;
object.initializePrivateVariableOne(20);
//OK! Now, privateVariableOne = 20
objet.incrementPrivateVariableOne();
In the above code stub, the following code represents the constructor -
ExampleClass(int publicVariableValue) {
//This is the constructor
publicVariableOne = publicVariableValue;
}
It takes in an integer and assigns its value to publicVariableOne.
To instantiate an object of the class where the value of publicVariableOne
will be 30, we do the following:
ExampleClass object(30);
Now, there’s another way of instantiating values in the constructor:
ExampleClass(int
publicVariableValue):publicVariableOne(publicVariableValue) {
//This is the constructor
}
Example- Create a Dog class that stores a dog’s age and the name and has
methods called bark and eat.
#include<iostream>
#include<string>
using namespace std;
class Dog {
private:
int age;
string name;
public:
Dog(int dogAge, string dogName) :age(dogAge), name(dogName) {}
void printDogName() {
cout << "Dog Name: " << name << endl;
}
void printDogAge() {
cout << "Dog Age: " << age << endl;
}
void bark() {
cout << "WOOOF WOOOOF!!" << endl;
}
void eat() {
cout << "I'm eating right now. Don't bother me!" << endl;
}
};
int main() {
Dog henryTheDog(2, "Henry");
henryTheDog.printDogName();
henryTheDog.printDogAge();
henryTheDog.bark();
henryTheDog.eat();
}
Here’s the output -
Dog Name: Henry
Dog Age: 2
WOOOF WOOOOF!!
I'm eating right now. Don't bother me!
Press any key to continue . . .
Chapter 11: Misconceptions About Coding
Before we dive into this, something should be said about coding. You
should not get into it, especially as a career if you don't really like it if it is
not something you want to do. Certain people think that being a coder will
make you happy, especially when you start earning big bucks. Seriously,
unhappy, it is something you should find a way to sort out and deal with
inside.
Using coding as a way to escape will only last for so long. Coding is not the
way to the proverbial Nirvana or Utopia. Coders also have challenges
peculiar to their jobs. Later in this book, we'll talk about some of the
challenges coders face. True, being able to make something out of nothing
literally comes with some fulfillment, sometimes a lot actually, and it also
gives confidence. But if you're looking for happiness, you won't find it in
coding or in any other career for that matter. Of course, you won't find it in
a person, at least not for long. You are responsible for your own happiness,
just as we all are responsible for our happiness. Now that we've got this out
of the way let's do a deep dive into misconceptions about coding.
Coding Will Make You Wealthy
Indeed, coders earn good money, and they are some of the top earners in
many areas. But then again, the fact that you earn well will not make you
rich or wealthy. What will get you wealthier is actually your financial
habits; your ability to take the money and then multiply it. You don't have
to be a programmer to do this. But then again, being a programmer gives
you more room to earn more money, and therefore, more opportunities to
become wealthy.
It's only for the Young
They say you can't teach old dogs new tricks, and maybe you can't, but then
humans are not dogs. And really, I have always believed that any skill can
be learned. You might never become an elite in that skill, but I believe with
the right tools and effort, you can become proficient at almost any skill, this
includes programming too.
They say it is only for those who are from 18 – 30 years. This could not be
further from the truth. It is true that most of the popular coders, or any of
those who've really made money from this, started out at an early age:
Zuck, Larry Page, Gates, and many others. I just saw on Twitter today, a 45-
year-old man who got his first job as a developer, previously having a
career in accounting. Admittedly, it would be more difficult to say a middle-
aged man or woman to get a junior developer role (entry-level
programmer). For some reason, tech firms employ mostly young people.
One reason is that most tech firm startups are owned and run by the young,
and many older people themselves believe that coding is for the young, so
they don't even bother getting into it.
You have To Be a Math Guru to Code
The fact is the amount of math you know at the moment is probably enough
for you to learn how to code. At least at entry-level, high school
mathematics is good enough for you to begin learning to code. Some people
have asked, "What's the connection?" Why do some people think that you
have to know mathematics to code? I believe I have the answer to that
question. Most universities, which offer computer science or computer
science-related degrees, do have a lot of mathematics in their curriculum. In
fact, departments of mathematics and statistics in many colleges work hand
in hand, and a lot of time, they take the same or similar courses. In some
colleges, the departments of math and computer science are together. So
you have something department of Mathematics and Computer Science,
just like you'd have Mathematics and Statistics in some colleges. This, I
think, is how the talk of you being a math guru came up.
For beginner coders, you're just beginning to learn how the Internet and
computers really work. You're learning the jargon associated with the field,
learning about FTP (file transfer protocols) and debugging, and all the other
stuff. Don't forget you have Google, and, as a beginner, virtually all the
problems you'll face have been faced by someone else. And the
documentation or solutions are somewhere on the World Wide Web. All
you need to do is just find it.
Now, this is where your Googling skills will come in. Learning the
vocabulary associated with the language you're learning will help you find
solutions online easier. At this point, especially when you're teaching
yourself, it is a thing of trial and error, Googling, and all through this
process, increasing your knowledge. Of course, there's a bit of logic
involved in coding. Apart from the little mathematics, you'll actually be
doing a lot of copy and pasting, with little edits or tweaks. Although I'd
advise, you type in the code instead of copying and pasting. And really you
don't need any mathematics to do this. In fact, those who came from fields
where no Mathematics was needed, such as those in humanities, seem to
know how to do this well. Remember the term papers.
Some codes look like equations true, but then there are plug-ins and add-
ons for such things. Some people live for such things, and most of the time,
these calculations have already been taken care of in one way or the other,
and all you'll need to do it tweak it for your own use. So for web
development, you don't need much of mathematics. But if you intend to go
into video gaming, or you want to work in some high tech places like
Google, Goldman Sachs, NASA, then yes, you'll need to know
mathematics, loads and loads of it. For those doing AI, Crypto and other
related fields, some of the math needed is even above college undergrad
level, yeah it's that essential.
So what I'm basically trying to say is that for entry-level coding, don't
bother about mathematics, because you already have enough knowledge for
that. As you delve deeper, though, you'll realize the knowledge you don't
have or need and do whatever it takes to get there. But by this time, you
should already know enough coding to work in a variety of places where
coding is required.
The fact is that there are not many programmers that really known
mathematics, so knowing it will give you an edge, especially when it comes
to getting a job. But as a beginner or someone who will build CMS (content
management systems), you know all the math that you need.
Programming is Only for Geeks and Nerdy Fellows
The fact is that programming doesn't make you a geek. You're a nerd if you
are, and you're not; if you're not, it has nothing to do with programming.
People also think that programming is for the uncool gang, you know the
social misfits, the socially inept and awkward. Now, nothing could be
further from the truth than this. Coding doesn't turn you into any of this, nor
is it only for those who have some sort of social problem. Coding is also
done by some of those we'd consider cool. Coding is now seeing use in
clubs, wherewith code you can decide the kind of music to be played. Or
you can even write music with code, for clubs and other fun places.
Programming is Only for Men
Of recent, certain companies such as Andela have entirely changed that
notion, with the training and employment of female coders. Programming is
not gender-based; anybody, irrespective of gender, can do it. The reason
why we have many more males in coding than women is the reason why we
have more men in engineering and science and related fields. Men seem to
be naturally drawn toward STEM, while more women seem to gravitate
towards the humanities, art, and fashion. And of course, the self-limiting
belief and talks of people always telling women they can't succeed in
STEM-based fields. But we know all these things are wrong. Coding is
gender-neutral, given the same opportunities; women can code as good as
men can. And did you know that the first programmer was actually a
woman? Her name was Ada Lovelace, Countess of Lovelace, a British
Mathematician and writer. She was born in 1815, and she died 36 years
later. In fact, at about that time, most of the programming work was done by
women. It was as an offshoot of their secretarial duties. As time went along,
though, things changed.
To Be a Programmer, You need a Degree in Computer Science
Or the very least, a degree in STEM. This is one very big lie that a lot of
people have been sold, by who? Really I can't tell. Perhaps some 15- 20
years ago, a higher institution was the only place where you could get learn
coding. And then you had to have taken a degree in computer science. But
now every Tom, Dick, and Harry can learn how to program. In a university,
it will definitely take you longer to learn how to code, and of course, there'll
be students debts to be paid. However, it will definitely give you a good
learning platform and better preparation to learn many other programming
languages and also give you better career opportunities in tech. However, it
is not the only way. Just online with Freecodecamp, Coursera, or Udemy
and uncountable others, you can learn how to code at your own pace. There
are also coding boot camps, where you can learn how to code and meet
other students like you. The fact is that you'll just need to be persistent,
know what you want, and create a schedule for yourself to follow. With
this, you'll learn code in like a quarter of the time it will take someone
following a university curriculum to learn how to code.
Chapter 12: Bash
Why is this the case? Well, the calls to mv can fail and we won't know
about it. This is because the script is coded to swallow output and errors.
How do I know this? The clue is in the redirect code: > /dev/null 2>&1.
This has the intentional effect of not letting us see the result of the
preceding mv operation.
So, as per metric 7, we need to at least record if an exception occurs in the
calls to mv.
In regard to inadequate abstraction, the file name can be made into a
constant. Then, the constant can be referenced in the script. This is better
than embedding the name as a literal string value, mainly if the file name is
used in multiple places in the script. A downstream maintainer might be
tasked with changing the script and could easily forget to change the file
name in all areas. Defining the file name as a constant avoids this
unpleasant possibility.
So, with all of the above observations in mind, Listing 1 is the modified
version of the Bash code.
readonly fileName='testfile.txt'
errorHandler() {
echo $1
echo $2
if [ $2 -ne 0 ] ; then
echo "Failed in errorHandler $1 Exit code is $2"
fi
}
cat $fileName |
while read line ; do
echo "Line read: $line"
outputDirectory=${line##* }
echo "Output directory: $outputDirectory"
mv $outputDirectory/streamFolder/output/*.log
$outputDirectory/streamFolder/output/archive/ > /dev/null 2>&1
errorHandler "first call to mv", $?
mv $outputDirectory/streamFolder/output/*.txt
$outputDirectory/streamFolder/output/archive/ > /dev/null 2>&1
errorHandler "second call to mv", $?
done
Now, any failures that occur during execution of the code in Listing 2
appear as illustrated in Listing 3. These errors can be logged to disk if
required by adding more code to the errorHandler function.
Also noteworthy in this example was the fact that we iterated twice through
the metrics. Again, this is a good practice - making small, focused changes,
reviewing the changes, and adding more minor changes. The combination
of the small changes adds up to a far better end result and the code can be
tested carefully as you go.
One noteworthy caveat is in relation to spacing. There might be a
temptation on the part of a Java (or other high level language) programmer
to introduce spaces into Listing 2. This might be done to try to improve
readability. One of the things about scripting languages, such as, Bash and
Python is that they are often very fussy about spaces, indentation, and so
on. Adding spaces to Bash code can introduce hard to find errors. So, be
careful with readability requirements!
Up to this point, we've seen the metrics in action in C code and now in Bash
scripting. How can the metrics approach be applied to Python code? Let's
find out.
A Python example
Given the following Python code.
f=open('myfile','r+')
f.write('abcdef012345')
As usual, let's apply the metrics to the Python code. Again, here is the list of
metrics.
1. Too short variable names and has no usage context
2. Code that provides no context or obvious purpose
3. Uneven spacing
4. Uneven parameter type definition
5. Incomprehensible code
6. Code that is too long
7. No exemption handling
8. No automatic resource management
9. External calls that are not contained in separate methods
10.
Inadequate abstraction - need for higher level code
11.
Code that is difficult or impossible to change
I would say that the following metrics are violated by the Python code:
Variable names that are too short and provide no usage
context
Inconsistent spacing
No exception handling
No automatic resource management
External calls that are not contained in separate methods
Also, we have some assumptions lying at the heart of the Python code
example.
What are the assumptions? Well, the first line assumes that the file already
exists and the second line in turn assumes that the first line was successful.
A simpler and sturdier version is illustrated in Listing 4 where we use the
standard exception management of the Python language. Also, I've tried to
improve the file handle name by giving it some context in the wider
program.
Listing 4 - Incorporating better naming and exception management
try:
logfile = open('myfile', 'r+')
logfile.write('abcdef012345')
except IOError:
print('Encountered an error')
Now if the file is deleted before the script runs, then you get a meaningful
message rather than a runtime failure. It's essential always to remember that
when your code interacts with system resources (such as files), you're
handling somebody else's property! System resources are owned by the
system, so you have to handle them with care.
The moral of the story is to keep it simple and try to avoid assumptions.
Mother nature enjoys assumptions; they give her an opportunity to show us
who's boss!
The addition of exception code has still not produced particularly reliable
operation. We are still relying on the file existing in order for the code to
work. To fix this, before opening the file, we can first check that it exists as
illustrated in Listing 5:
Listing 5 - Incorporating an existence check
try:
if(os.path.isfile('myfile')):
logfile = open('myfile', 'r+')
logfile.write('abcdef012345')
else:
print('File does not exist')
except IOError:
print('Encountered an error')
So, the code now uses isfile() to check if the file exists before attempting to
open and update it. This means that we have now removed the assumption
about the file existence. If the file does not exist, then we'll know upfront,
rather than relying on an exception.
Chapter 13: Regular Expressions
inputs. First we present the necessary characters for the formation of simple
Characte Functions
rs
/…/ Patterns are enclosed in between two forward slashes like this
/a/. This matches a single alphabetic letter ‘a’ in an input
string “ant”.
[…] The braces represent a character set. The character set
matches any of the characters within the braces with no
exceptions for special characters and escape sequences, for
example [abc] would match the first three letters of the input
string “abcdef”. A range can be represented with a hyphen
like this [1-9], which matches any character from 1 to 9, same
as [123456789].
\ When the backslash character precedes a character, it makes
the character unique and gives it a special meaning different
from its literal meaning.
\d The lower case letter ‘d’ preceded by a backslash represents a
numerical input and matches a single digit, for example /\d/
matches digit 3 in the input string “32 Highway”.
\D The upper case letter ‘D’ preceded by a backslash represents
any non numerical input and matches a single non digit input,
for example /\D/ matches ‘H’ in “32 Highway”.
\w The lower case letter ‘w’ proceeded by the backslash
character represents a single alphanumeric character in the
range 0 - 9, a – z, A – Z including the underscore.
\W The upper case letter ‘W’ preceded by the backslash character
represents a non alphanumeric character like the followings;
@, %, * and so on for example /\W/ matches the ‘@’ in the
email address feyi_dos1@yahoo.com.
Step 1:
We create the regular expression pattern for the first letters which normally
should be a single capital letter and in some exceptional cases can be more
than one. We use the character set A to Z to represent the pattern as shown
below:
[A-Z]+
Remember the quantifier ‘+’ implies one or more occurrence of the upper
case character set A to Z. We need this representation to be followed by
lower case character set a to z. The lower case character set is represented
as follows:
[a–z]+
Now we want a combination of the two sets, to achieve this we combine the
two sets as shown below.
[A-Z]+[a-zA-Z]+
Meaning you can have a noun class written in upper cases all through and a
noun class starting with an uppercase character, followed with a
combination of high and lowercases. In summary a noun class must begin
with a capital letter. The quantifiers ensure there is at least an alphabetical
input for both the upper and lower cases.
Comple Functions
x
characte
rs
$ Matches a character occupying the last position in the input
string, for example /r$/ matches the last alphabetic character
‘r’ in the input string “reader”, but finds no match in the input
string “read” or “READER” for the match is case sensitive.
^ Matches a character occupying the first position in the input
string. For example /^e/ matches ‘e’ in the string “eat”.
. Represents a single character input and matches the character
input. For example the regular expression /.n/ matches the
letters ‘In’ in the string “Into” and /.o/ matches the letters “to”
in the string “to”.
A|B The ‘|’ special character also called the ‘OR’ operator matches
A or B, whichever it finds in the input string. For example the
regular expression /boy|girl/ matches ‘boy’ in the input string
“boy scout”, girl in the input string “girl scout” and girl in the
input string “girl or boy” whichever it finds first.
\s Represents and matches a white space character, a tab or a
form feed.
\S Represents and matches a non-space character.
(…) The capturing parentheses match their contents as single
entities and also remember the match for future usage. \1 to \n
denotes the sequence number of the parenthesized matched
items to be remembered. For example, the regular expression
/\w+(\s)\d+\1\w+/ matches the string “No 42 Highway” in the
input string “No 42 Highway road”. The only capturing
parenthesis is remembered with ‘\1’ in the expression and
applied as a white space between “42” and “Highway”.
(?:a) The expression (?:a) represents a set of non capturing
parentheses that match but do not remember the match as
done by the capturing parentheses. The main purpose of the
non capturing parentheses is for creating sub expressions to be
matched in a regular expression. For example in the
expression /(\w)+\s(?:\d+)\s\1/ the numeric part (?:\d) is
matched but never remembered.
A(?=B) This acts like a look ahead. It matches the expression A
provided that it is immediately followed by an expression B.
For example the regular expression /Coca(?=Cola)/ matches
“Coca” if and only if it is followed by “Cola” and it is case
sensitive. The regular expression /No(?=\d+)/ matches “No” if
and only if it is followed by one or more numbers.
A(?!B) The regular expression matches an expression A provided it is
not followed by an expression B. For example the regular
expression /No(?!\W)/ would match nothing in the strings
“No%” and “No@” but would match the “No” in the string
“No1 Gateway”.
[^abc] This expression represents a complimented character set that
matches any character set not in the complimented set. A
range can be represented with a dash. For example the regular
expression [^abc] performs the same function as the regular
expression [^a-c] and matches the character ‘r’ in the string
“car”.
Step 1:
The alphabetic character is represented with the regular expression /[ a-zA-
Z]/ which matches any single upper or lower case alphabetic input. We
expect that our username should start with a minimum of a single
alphabetical input, for this reason we make use of the quantifier “+” to
arrive at the following expression:
/[ a-zA-Z]+/
Step 2:
We also expect that the above may be followed by a combination of
alphanumeric characters. The regular expression /\w/ gives a good fit. The
quantifier “*” (zero or more times) is used with the expression for a
complete representation as shown below:
/\w*/
Step 3:
The final step is to combine the alphabetic regular expression with the
alphanumeric regular expression such that the alphabetic is matched if
followed by an alphanumeric expression or not. This is as presented below:
/[ a-zA-Z]+\w*/
Examples of complex patterns are the email address and dates. We shall be
formulating the email address as a follow up practise to our username
implementation. An email address is has two parts; the username part and
the server address part separated by the ‘@’ sign. Therefore the formulation
process is divided into two stages.
/(\.)[A–Za-z]{2}/
The quantifier {2} accepts two character length input only. Now bringing
the components together we have the regular expression:
/@[a-zA-Z]+\w*(\.)[A–Za-z]{2,3}(?:\1[A–Za-z]{2})*/
The above regular expression would match the server name “@yahoo.com”
in the input string “123@yahoo.common”. Please note that the country
code component which is enclosed in a non-capturing parenthesis ‘(?:\1[A–
Za-z]{2})*’ has been made optional with the use of the quantifier ‘*’.
From here on, you can design and implement any desired pattern for any
particular validation purpose, all you need is a little more practise though.
Remember, practise makes perfection. I wish you success in your practise.
Chapter 14: Data Structures
List
each component can have another element before or after it. A linked list
consist of nodes that contain data. Each node, or position gets a certain
ordering number, depending on its ordering in the list: we talk about the
first element, the second etc. Each node contains a value; it can be an
integer, a string etc. When we refer to a specific position (for example when
we talk about the first element), there is maximum one entry that may
satisfy our request. This means that we cannot have two or more elements
in a position.
The first node is called head. Internally, each node points to the next one,
and the last one points to null. In Python we do not have to worry about
pointers.
Implementation: We can name our list with a name of our liking, usually
something that represents its functionality (be careful not to use a built-in
python name!).
Lets name our list a.
In the brackets that follow the name of our list, we place the index, the
position which we refer to:
a[0] refers to the element at the first position (position 0). We need to
assign a value in this cell.
a[0] = 5, assigns 5 in the first node of our list.
So, we have:
list[index] = value
For example in our previous list, we can do b.insert(0,3), which will give
us:
b = [3,2,5,4,7]
We can remove an element that contains a certain value:
list.remove(x)
Note that this will delete the first element that contains this certain value.
For example in our previous list, if we do b.remove(2), we will get:
b = [3,5,4,7]
Tuple
Explanation: Tuples serve a similar functionality with lists, with the main
difference being that tuples are immutable: as soon as you add your data in
a tuple, they cannot be changed or deleted and it is not possible to insert
new data. The only way to perform such operations is to create a new tuple
containing the new or edited data etc.
In terms of syntax, tuples use parentheses to store the data in place of the
lists’ square brackets. There is also the possibility not to include
parentheses at all, and just separate data with a comma.
When we need to refer to a certain position in the tuple, for example
position 0 (first element), position 1 (second element) etc, square brackets
are used.
Implementation: We can create an empty tuple named t:
t = ()
We can also create a tuple that contains some numbers:
t_2 = (9,4,6,8,2)
or:
t_2 = 9,4,6,8,2
Now, we can refer to a certain element of the tuple, like for example the
first element:
t_2[0] = 9
Dictionary
Explanation: A dictionary is used to store data by using a unique key for
each entry. Key is somehow serving the same functionality as indices in
lists and tuples, when we want to refer to a certain element. The values
where each key refers to are not necessarily unique. Dictionaries are
mutable, so we can add, delete or modify the elements in it.
The entries of a dictionary are contained between curly braces {}. Each
entry is in the form key: value.
Implementation: We have a dictionary d:
d = {}
and we can populate it with key-value pairs:
d = { key1:value1,
key2:value2,
key3:value3,
...
}
Set
Explanation: A set is a collection of items that in contrast to lists/tuples, it is
unordered. There can be no duplicate elements. Sets are efficient when we
want to search if an item is contained in them or not. Later on, we are going
to talk about hash functions, which implement efficient searching. We can
add, delete or modify the items in a set. The set items are contained in {}.
Implementation: We can define an empty set s_empty:
s_empty = {}
or we can construct a set of certain items, like a set of fruits:
s_fruits = {‘orange’, ‘banana’, ‘apple’, ‘peach’}
or we can add multiple items in the s_fruits set using the update() function:
s_fruits.update([‘grapes’, ‘mango’])
s_fruits = {‘orange’, ‘grapes’, ‘banana’, ‘cherry’,‘apple’, ‘peach’, ‘mango’}
Array
Explanation: An array consists of an ordered collection of elements. We can
refer to each item by its index in the array. An array can have dimensions:
the widely used 2-dimensional table that we encounter very often in our
everyday life, but we can also have more dimensions. In computer science
theory, the difference between an array and a list is the way data are stored
in memory, which affects how we access an element. A list allocates non
sequential cells in memory, therefore they need a reference for the next cell;
this is what the index does. Lists support sequential access, where you need
to search an element by examining the first element, then the next one,
afterwards the third one etc until you find the element you are looking for.
An array allocates only sequential cells in memory. Arrays support
sequential access, as well as direct access.
Implementation: You may have noticed that Python lists have some array-
like features, according to the list analysis above. Python in fact uses array
functionalities in lists, like for example direct access to a certain position.
However, there is an array structure in Python, but it should be imported:
import array
We need to specify the data type that this array contains and also the list of
elements that the array is going to contain when we are creating it. For
example:
a = array.array(‘i’, [1,2,3])
Yes, array keyword is written twice, because we are calling the array
module from the array library. It is easier to rename the imported library
array though:
import array as arr
a = arr.array(‘i’, [1,2,3])
‘i’ refers to int Python type. Below is the list of all supported Python data
types and the letter they use to indicate this data type when we construct an
array:
Stack
Explanation: Stack is used to store items in the Last in – First out (LIFO)
manner. Operations like insert element (push) and remove element (pop)
can occur only from the ‘upper’ end of the stack. An overflow can occur if
we exceed the maximum size of the stack, while an underflow can occur if
we try to delete an element from an empty stack.
Implementation: In Python a stack can be implemented by using a list
structure. We can create a simple stack:
stack = []
# Pop elements from the stack
stack.pop()# ‘3’
stack.pop()# ‘2’
stack.pop()# ‘1’
Queue
Explanation: A queue handles item in the first in – first out (FIFO) manner.
We can add (enqueue) items from the ‘end’ of the queue and delete
(dequeue) items from the ‘beginning’ of the queue.
Then we can create a queue by calling the method Queue in that module.
We can add (put) elements and we can delete (get) them in the FIFO way:
q = queue.Queue(maxsize = 100)
q.put(‘a’)
q.put(‘b’)
q.put(‘c’)
# q = [‘a’,’b’,’c’]
q.get()# ‘a’
q.get()# ‘b’
q.get()# ‘c’
Graph
A graph is a representation of a set of objects (nodes or vertices V) where
some of them are connected with links (edges E). Formally, a graph G is
defined as pairs (V, E) .
We can dynamically add and remove vertices and edges.
Note that the above is an undirected graph: this means that the connections
between the vertices have no direction, for example ab = ba etc.
In case of directed graphs there are directed arrows as edges,
and we can move only towards the direction of the arrow.
A sequence of edges that connect a vertex with another, either directly or
indirectly, forms a path. \
Tree
Trees are a subtype of graphs, which needs to satisfy the following
requirements:
- It needs to be acyclic: to contain no cycles
- It needs to be connected: Any node should be reachable through some
path, so there are not ‘stray’ nodes
Typically, the tree has a structure of a root node and children nodes. Root
node can be only one and it can have any number of children nodes
(directly connected to the root nodes). Any child can have any number of
children etc. Nodes that do not have children are called leaves.
Chapter 15: Algorithms
Algorithm
In the coding phase, all the modules defined by the modular design will
become a program; that is, the final application will consist of the sum of all
the programs that are designed. But first, we must determine what the
must be used.
Pseudocode
The pseudocode is an algorithmic programming language; It is an
intermediate language between natural language and any specific
programming language, such as C, FORTRAN, Pascal, etc. There is no
formal or standard pseudocode notation, but each programmer can use their
own.
An algorithm written in pseudocode is usually organized in three sections:
header, declarations, and body. In the header section, the name of the
algorithm is written, in this case, add. In the declarations section, some of
the objects that the program will use are declared. In the tutorial of the
language of Abrirllave, the different types of objects that can be used in a
program are studied in detail, such as variables, constants, subprograms,
etc. For now, note that, in this example, the variables a, b, and c, they
indicate that the program needs three spaces in the main memory of the
computer to store three integers. Each of the variables refers to a different
memory space.
Flowcharts (Ordinograms)
Algorithms can also be represented, graphically, by means of flowcharts.
Flowcharts can be used for other purposes; however, in this tutorial, we will
only use them to represent algorithms. Such flow charts are also known as
audiograms. In other words, an ordinogram graphically represents the order
of the steps or actions of an algorithm.
Pseudocode and flowcharts are the two most used tools to design algorithms
in structured programming. Although, between both types of representation,
there are the following important differences:
The person who designs an algorithm must be aware that all the properties
of an algorithm will be transmitted to the resulting program.
Chapter 16: Logical Switches
allow for many different conditions to be checked and have varied output
depending on the value we are checking against. They look cleaner than a
series of ‘if’ statements, and there is some additional functionality that can
be done with switches that sometimes makes the desirable. Let's look at a
switch (variable) {
case condition1:
// some code based on what you're doing
break;// exits the switch loop
case condition2:
// more code for what happens for this condition
break;
case condition3:
// you can have as many cases as you like
break;
default;
// code to do if none of the other cases are true
In this example, we can see the format that switches take. The term
'variable' is a component you will use to measure some varying quantity in
your sketch. The conditions, one, two, three, as many as you like, are
values you are comparing a variable against. They can be anything,
numbers, letters, words, even other variables, or the results of functions it is
kind of crazy what you can put as a condition. This is why they can be
extremely powerful in coding. You can make complex conditions or simple
ones, and both will have a clean, readable layout that has a very easy to
understand flow when you read it. This readability in your code is so
important for us humans to understand what is going on with it.
The code within each case will continue until it reaches the word ‘break’
which is an Arduino keyword and this tells the compiler that it should exit
the current function it is doing. In the case of a switch, it will exit the
switch when a break is encountered. If a break is missing from the code, it
will instead continue on and run the next line of code below in the next
case, which may leave unexpected results. It's best to make sure you add
break to your code at the same time as a case to make sure the code you’re
writing will flow properly.
Let's look at an example sketch:
File → Examples → 05.Control → switchCase
Okay, we start off with initializing our sensor minimum and maximums in
the form of constants that the coder determined from experiment. In setup()
we turn on serial communication so we can use our serial display. In the
loop function, we declare and initialize the variable we will use to read our
sensor, sensorReading. Zero to Six Hundred is a lot of cases to cover if we
just want to display relative brightness of the display. The user wanted four
data points to generalize the brightness, ranging from zero to four. They,
therefore, used the map() function, along with sensorReading, sensorMin,
sensorMax, 0, and 3 as the arguments, to scale the reading should be within
a 0-3 range instead. Notably, the map function will scale to the nearest
integer so we can safely know it will only contain four data points.
We now set up a switch to check the reading. We send ‘range’ to our
mapped sensor reading and have the switch as our variable. Our cases are
0, 1, 2, 3, which corresponds to the expected data range of our variable,
good so far. Now, if range got mapped to 0, we will print, dark. If range
gets mapped to 1, we will print dim. For range 2, medium, and for range 3,
bright. The user added a 1-millisecond delay for stability, forcing it to read
once per millisecond instead of much faster. Essentially the chip clock
speed, which by default, is 16Mhz or sixteen million instructions per
second.
Let's take a look at another switch example. Open up:
File → Examples → 05.Control → switchCase2
In this next example, again we see and initialize ‘Serial’ communications
like we've done before. Then we initialize our pins to OUTPUT using a
‘for’ loop, cycling from pins two through seven by one each pass. Next, we
have to check if we have received a character input from the serial port
(greater than zero means not FALSE), we will then create an integer which
will read the input from our keyboard. Alphanumeric keys come in the
form of ASCII characters, so for example 'a' = 97, 'b' = 98, 'c' = 99, etc.
This is why we record the input as an integer from Serial.read().
Next, we reach our switch, which varies based on the value we recorded
from our keyboard input inByte. We have set five possible cases and a
default in case we get a character other than our case values. For any
character a, b, c, d, e, we will toggle an LED to high. For any other value,
we will sequentially turn the LEDs off going from lowest to highest, using a
‘for’ loop.
This example shows that you can base your cases off of almost any kind of
variable. It doesn't have to be an integer. They can be anything you feel
you need to check what is happening in your sketch and react to that
condition.
Switches are a fantastic way to keep your code elegant and organized.
Chapter 17: Coding Practices
Contained in this will be some of the best practices you can adapt to take
conventions.
Here are some best practices for your comments that will help other readers
understand you easier:
Start with a summary of the sketch and what it will
accomplish. Provide any links if it helps the understanding
of your design. Try to approach your block comments from a
user-friendly stance as much as possible to give a clear idea
of what you will be doing.
Write in the active voice. Use a clear, conversational tone for
your writing, as if you were speaking to another person
standing next to you.
For instructions to the user, use the second person, to invoke
in the user that they should be the ones to carry out your
instructions.
Use short descriptive phrases rather than complex phrases. It
is easier to understand one simple idea at a time.
Be explicit about what you are doing with your actions. For
example: “Next, you'll read the value of the sensor on pin
thisPin.”
Avoid phrases or words that are ‘fluff’ or do not contribute to
the explanation, e.g. you see, you'd want to, etc. Instead, skip
those words and give a statement that's direct to the point,
e.g. set the pins.
Check your assumptions, make sure you have explained all
of your ideas and haven't left something that can only be
explained ‘in your head.’
Give a description for every variable or constant with a
comment of its purpose either before, or in line with the
variable or constant.
Similarly, give an explanation of a block of code that you're
about to perform before the instructions are executed, so it's
clear what's about to happen.
Every loop should have comments explaining why this loop
exists (e.g. what it is doing), and a verbal explanation of its
condition if it’s still not clear.
Do not create one letter variable names! Your naming conventions exist so
that you can, at a glance, read your code without having to refer to other
places to understand what is going on.
Write code that is reusable or modular
Seriously, this cannot be overstated how valuable this step is to write clean
code. By knowing all the pieces you will need to accomplish your sketch's
task ahead of time conceptually, you can successfully plan ahead and use
things like functions in a smart way.
Keep things organize and together
If you make a function to smooth an analog sensor, make sure that's all it
does. Don't start doing other parts of your code within that function. If your
function needs to, you can have it call yet another function to help it
accomplish its task. Again think modular (small pieces make a big part).
Make yourself a toolbox
Make functions that do specific things. Then use your tools as needed in
your code.
Keep your sketches
Even if you think you won't need a sketch you made anymore, keep them.
If you need a piece of code that you've already written for another project
and you have followed these practices, you can simply snag that piece of
code and drop it into the new project you're working on. Brilliant!
Write your functions in a generalized way whenever possible
for these exact reasons
To put this simply, it means that if you were making a function to draw a
square, make a function to draw a rectangle instead since a square is a
special case of a rectangle, where the edges are equal.
Make sure your functions do what they say they will do
We didn't even touch on them in this document, and we are only going to
tell you they exist to tell you not to use them unless you're an advanced
user. They are the most likely ‘tool’ to cause the crazy, bad kinds of
problems from happening in your coding, and are notoriously tough for a
beginner to use properly. So avoid them until you are sure you know what
you are doing.
Embrace self-improvement
Understand from day 1 that as a fledgling coder that you will grow and
improve over time. Use each challenge you come across to try writing new
sketches as an opportunity to grow and hone your skills.
Reach out to the community for help and advice!
There are some really fantastic people in our big community of hobbyists
that are willing to help you learn and grow as an enthusiast.
Try to make things foolproof when you code
Try to make sure your for loops terminate, try to account for unexpected
inputs when checking values, try to constrain your data within expected
values. These ‘tedious’ steps are what keeps your program running smooth
and bug-free!
Know how to use debugging tools and techniques
It's a more advanced topic but learning about debugging tools and
techniques for large-scale projects such as robotics, or as a controller for
something like a pump mechanism will help expand your knowledge
further.
Write both brackets or both braces at the start then fill in the
date in-between
When writing functions, loops or anything with brackets and braces, this
trick helps to ensure that you will be closing all of your brackets and braces,
preventing unexpected results.
Try new ways to use your Arduino!
This is how you can really develop new skills. When you have more skills,
you can think of even more things you can do with the chip! The
possibilities with this micro-controller are nearly limitless and are bound
only by the limits of your imagination.
More Naming Best Practices
Functions follow the same rules as variables
The name should start with a lower-case letter, all one word, and additional
words are distinguished with capital letters.
Functions should use verb names to describe their function
Make sure the for loop variables are clear on what they
represent
Having a variable of x can work, but it really offers nothing to the person
reading your code for them to understand exactly what that variable is for.
Chapter 18: How to Be an Expert Coder in the Shortest
Time Possible
Coding is not the easiest thing to do; at least this is something almost
everyone new to coding will agree with. However, as you actually go on,
you'd discover that coding is actually not so hard, challenging, yes, and it
impossible, that is just at the beginning. You'll also discover that what you
might find infinitely difficult might just be learning your first language.
This is quite understandable as you're just getting into a new field. As you
learn more languages, you'll discover that it actually becomes easier. The
irrespective of the language that you've learned. This, I guess, is the reason
lots of coders advise that you learn HTML first. Although it's not a
programming language, it is very easy to learn and put into practice, and it
So how does one become an expert coder in the shortest possible time? In
fact, who's an expert coder, and how long will it take before someone can
be regarded as that?
The fact is that if you ask 5 different people in tech, they'll give you five
different answers about who an expert coder is. Here's the way I'd define an
expert coder. I consider an expert coder as one who can write good code.
Anyone can actually learn how to write code; writing good code, though, is
a different thing entirely. And this is where the tough part is, I think it
should be the aspiration of every coder to be able to write, neat, good, free-
flowing code.
Refuse To Be Intimidated
This is usually the first problem that beguiles most people learning code for
the first time. Especially those who think it is for the mathematical
geniuses. It all starts in your mind; you have to rid yourself of any form of
intimidation. "Anything can be learned," never forget this phrase. I'm not
trying to excite you up like a motivational speaker, though I'm not saying
this is bad in any way, I'm just trying to present the facts before you. And
with the array of resources available on coding, you'd be able to find a class
or two that totally resonates with your learning pattern.
Learn How To Learn
This, for me, is the most important skill every developer needs. Irrespective
of how far you've gone into coding, or how little about coding that you
know. Learn how to effectively learn, because you'd continue learning as
long as you're a coder. There's no point in the life of a programmer when he
can really say I have arrived, I have learned all that needs to be learned.
This character is something I have found amongst musicians, both
professional and those who do it as a hobby. When we meet at events and
someone does an introduction, which goes thus, "meet my badass
keyboardist friend," and then the badass keyboardist will say something
along these lines "please pay him no mind, I'm just a learner." And as the
introductions go round, and someone introduces someone who he thinks is
an excellent musician, the instrumentalist friend says, "I'm still learning."
At the event, a lot of times, it would turn out that a lot of the guys are
actually excellent instrument players. At first, I thought it was fake humility
until I started learning to play the keyboard. And the better I got, the more I
realized that there was so much more to learn about playing the instrument.
This is something most programmers understand; there's always something
to be learned. There are new code bases, new challenges you encounter as
you tackle novel projects, both personal and at work.
The rate at which the tech world is changing is astronomical. There are new
updates to languages, new tools and frameworks, and many other new
features coming out every day. A developer needs to be able to keep up;
otherwise, he/she will be left behind.
Learning is not easy. If it were, well, we'd have knowledgeable people
around us every day. If you really want to learn how to learn, then I'd
suggest that you take coursera's course. The course title is "Learning How
to Learn: Powerful mental tools to help you master tough subjects." At this
point, you'd agree that learning to code is a tough subject. The course is
free, and you'd be able to apply the skills and techniques you learn there to
any form of learning in your life, both technical and non-technical. This is
like the best free course I have taken all year, and I recommend it to
everyone who needs to or wants to keep on learning. It's going to make your
learning more efficient. I'll also suggest that you read Cal Newport's book
"Deep Work." The book contains strategies on how to learn faster and also
be more productive. It also has a very inspiring story about some guy
learning how to code and becoming very good at it and getting well paid. I
don't remember the fellow's name, but the thing is that this guy was an
entry-level accountant, but he wanted more, so he taught himself how to
code. And all these happened in less than a year.
As far as learning code is concerned, there'll be no point where you might
be able to say; I have learned it all; therefore, I know it all. Learning for a
coder is a continuous process; it never ends, the challenges, the pressure to
be the best you can be, it will not end. Perhaps until you decide to stop
coding, but one thing though that it that learning coding will get easier as
you go along. The better you get, the easier and faster it becomes for you to
learn more coding related things.
Learn To Write Code; Try the Hands-on Approach
There is the temptation by certain persons wanting to learn code to read all
the materials they can get on the language, read blog posts, and watch
videos before even writing a line for code. For effective learning, I'll say
you should begin writing code as soon as possible. That's another reason I
suggest you start learning from HTML; you can see the results of your code
immediately. You might think that you've gotten the concept of how to code
a certain feature because you saw the documentation, or you read it in a
book only to want to try it out, and you're stumped. This, I think, is one
reason I love freecodecamp, each concept you learn is paired with a
relevant exercise so that you can try out your hand on a concept. Until then,
no matter how much you think that you understood the concept from the
lesson until you do something with it, you can't be so sure. Something else
with coding is that things don't usually work right the first time; you'd be
stumped many times. So it's better you get used to getting stumped and
learning also to get yourself out of the quagmire.
Another way to reinforce learning faster is to use coding games, challenges,
and other interactive tutorials to reinforce learning. Hour of Code is one
coding game you might want to give a try, CodinGame is another coding
game you might want to try, it is more complex, but also you might be able
to put it on your resume.
Learn Computational Skills
Computational thinking is very important for a programmer. This is where
you learn to solve problems in the way a computer can interpret. These
skills are what people acquire when they study computer science. So you
see, a computer science degree is not a waste after all. Some of the topics
you'll encounter include loops, algorithms, recognizing patterns, amongst
others. These concepts will equip you with the skills to understand
programming languages easier and faster. With this knowledge, too, you
can take on more difficult projects and even design better products. Ideally,
the place you'll get this knowledge is from a degree program in computer
science from a university. However, there are online resources where you
can learn computer science for free or a token price. EdX, Coursera and
MIT OpenCourseware are some of the places you can learn about computer
science. You can also get videos on this YouTube channel.
Projects
You really can't say that you've understood a language well until you've
used it in a project. In fact, if you don't have projects in a certain language,
you might not be able to prove in a job interview that you really understood
a certain language. A project tasks you on most or all of the knowledge you
have acquired in a certain language. It reinforces what you've learned, and
also it pushes you to learn more. See, you don't have to wait until you've
gotten to the end of the course before you start attempting projects. Some
platforms like freecode camp have projects, real-life projects for real-life
organizations which you can tackle as a way to challenge yourself.
If you're looking to get into coding things very fast, you should start coding
with a project in mind, even without knowing jack about the language. It is
one easy way to learn about the features and tools. So you might decide that
you want to learn Android development, and then with your skills, you
want to be able to build an alarm clock app for your phone. So you go
online to search for resources on how to make that happen. In the process of
learning to build an alarm clock, you'll definitely learn a lot. It's a more
difficult route to use in learning, but it is a very effective one.
Tinker with Other Peoples' Code
This is after you've grasped the basics of whatever language you're learning.
At this point, it is time to find someone else's code, play around with it, and
see what happens. There are places where you can find code files; one of
them is GitHub. Open the file in your code editor and get to work. Try to
read the lines of code and try to see if you can understand what each line
does. If you can improve it, so if you have questions about the code, ask, if
you have comments, make them. And if, for any reason, you improved on
the code, upload it to GitHub or any developer forum you're on and see
people's feedback.
Join Developer Forums
This goes without saying. Development is not done in isolation. It's a group
of people building on what others have built and improving what others
have created. Most developers are open-hearted as far as sharing coding
knowledge is concerned. On these platforms, you can get people to answer
your questions, give you advice, share knowledge, and even get mentored.
Slack Overflow is a good place to be as someone learning to code. You'd be
inspired; you'd be challenged and encouraged by what you see in these
forums.
Chapter 19: Other Factors
your level of impacts plays a lot in determining the level of your success or
how best you are as a programmer. Truly, people will not measure your
experience from how happy you look when doing programing projects but
how your programming projects are impacting the lives of many people in
society. For example, there are some people who always feel happy after
spending the whole day without doing any programming tasks while others
feel unhappy if they do not handle any projects. Also, drinking alcohol
everyday can make a person feel happy. Therefore, your level of experience
and knowledge does not show how happy you are but how you use the
learned skills.
Several studies have proved that slacking off in computer programming not
only makes person’s programming logic weaker but also destroys his/her
tempo. Normally, we miss many things when we don’t attend the classes
just like drinking coke every day ruins both our teeth and internal organs.
Just like alcohol has impacts in our bodies, your success in programming is
measured through its impacts. We will see you as a weaker programmer if
you do not use the learned programming skills to create positive impact to
you or to the society.
Impact on Others
Before you consider yourself as the best programmers, it is important to ask
yourself about the impact you cause to other people when you are coding.
Okay, you may be like that you know how to code because it is the most
useful tool available for impacting the lives of many people positively. You
can impact people by either enabling them to get data easily, improve their
websites, or increase sales. Every person must have a goal in mind why you
are doing a particular job. One of the goals in programming is helping other
people achieve their objectives. You will be recognized as the best
programmers when you help others and organizations to succeed and at the
same time meeting your goals. I know it is sometimes difficult for most
programmers, but you can become the best programmers if you do this.
Getting started with finding your first job can be difficult. There is quite a
bit of competition. Many recent college graduates compete for the same
position as you.
Start putting yourself out there and seeking programming challenges. Think
of something that you want to do and then start looking into whether other
people have done it. If they have, look into the way that they did it and try
to find a way that you could do it yourself. If they haven’t, then this gives
dirty and start looking into and learning as much about things having to do
I’m going to say this right now: Programming is not easy. You have a long
and arduous journey ahead of you, and the truth about programming is that
to be a programmer means to submit yourself to constantly learning. At no
point in programming do you ever consider yourself “done with learning’.
One of the big problems they face when starting in this programming world
is that when you start you want to make complex programs, pages, and
professional applications, but at the critical moment there can be some
difficulties, even when you have the experience, for this reason, we decided
to share some tips to shorten the learning curve:
1-Know the origins first.
This does not mean that you completely learn the history of the computer,
but you must know it, that will give you the notion of how everything came
about, so you will know how everything works, from data to an operating
system.
2-Master basic concepts.
Know computer concepts such as what is a data, record, field, information
among others. As theoretical and boring as this may seem, it will help a
future to understand how multiple functions work and why they are made
that way.
3- Make an algorithm before starting to throw codes.
If you do not know what it is sincerely I tell you that you will less
understand what you do, this is a serious mistake that many programmers
make that we do not give importance to the analysis before starting, I advise
you that if you are starting as a programmer, you first practice informal
algorithms, then it happens to the computations.
This will open up your logic as a programmer and will make a kind of
connection between your mind and the computer so that both friends can
easily understand.
Eugene Gates
Introduction
here are various operating systems that you are able to work without there.
Each of them is set up to handle different situations and help you to get
different things done with your work. But you will find that one of the best
coding languages out there, the one that will help you to get the most done
while still being easy to maintain and work with, is the Python language.
There are a lot of coders and programmers out there who love to work with
the Python language. And as we go through this guidebook and learn a bit
more about this language and what it is able to help us do, you will not take
long before you realize why it is such a popular option to work with, and
why so many people love it. Some of the different benefits that you will be
able to see when it is time to work with the Python language includes:
Python is an easy coding language to learn how to use. If you have never
had a chance to work with any coding language at all, then you are going to
really enjoy working with the Python language overall. This is going to
make it easier for us to handle some of the coding that we are not used to,
and you will be able to catch on to some of the basics that come with
coding in Python and more in no time at all.
Python has a lot of power and resources behind it. Sometimes there is worry
that working with this language is going to be too easy that you will not be
able to handle some of the more complicated codes that you would like to
work with. The Python language is often going to be advertised as a
beginner's language, and this can keep a few programmers away from it.
The good news here is that the Python language is not just a good coding
language for beginners to get started with. It is also a good language that is
going to help you to get a lot of the different codes that you want. We will
take a look at some of the different options that you can do when it is time
to code, and we are going to spend some time on them in this guidebook as
well. And you will be able to handle them with plenty of strength that
comes in the Python language.
And if there are a few things that you may struggle within this language, or
that are not strong enough to handle, then you will be able to combine in
another language, while still relying on the Python syntax. You will find
that Python works well with a lot of other coding languages, and several of
the libraries that work with Python can help you to get this done. This will
ensure that the few tasks you need help with will work well, while still
choosing the Python language.
Python has a great standard library to work with. For the beginner coder,
and someone who is just getting started with some of the work that comes
with the Python language, or any coding for that matter, you will find that
the regular library of Python is going to have all of the parts that you need.
You will be able to use the standard library of Python in order to handle all
of the coding that we are going to explore in this guidebook.
Python has a lot of extensions and other libraries that can help to add to the
capabilities that come with this language. Even though there is a lot that we
are able to do when it comes to working on the Python language, you will
find that there are also some good extensions that you can take a look at as
well. These are going to be good options to go with because they will
extend out what the Python language is able to handle, and will make it
easier to handle things like science, math, machine learning, data science,
and so much more.
The kinds of extensions that you are going to use will really depend on
what your goals are overall with the language. If you want to work with
machine learning and this language, then there are a lot of great libraries
and extensions that you are able to choose to help with that as well. But
there are also some that work with other features and capabilities as well, so
you need to make sure that you are choosing the right one for your needs.
Python has a large community that can provide beginners with the support
and helps they need. At some point, there will be some part of coding that
you are not sure how to do, or you are going to run into something that may
not make sense when it is time to work on your coding. This is going to
happen with many beginners, so it is nothing to be worried about But since
there is a nice community out there of other programmers and coders who
like to use Python, you will be able to find the assistance that you need in
no time.
This community will be there to help you to get going overall, and they can
answer all of your questions, make sure that you understand what is going
on, and just provide you with all of the resources that you need to make
sure you are doing well. You can visit this community as often as you need
to make sure that you are able to handle all of the different coding options
that you want to work with too.
Python is considered an OOP language that relies on classes and objects to
keep things nice and organized Right now, that may not seem to mean all
that much for you. But in the long run, it is going to help us to make sure
that we can keep all of the parts of our code organized and easy to work
with. The code is set up so that you can create the classes that you need
while still ensuring that you can add in the objects of the code and find
everything later on.
This was not something that we were able to find with some of the
traditional coding languages out there. These could sometimes be harder to
work with than Python and other options because they are not going to be
that organized and things can move around on you. But in Python, the code
is going to rely on those classes and more to ensure that it works the way
that you want, and that you are able to find the objects that you need.
Python is a great general-purpose language that is easy to learn, has all of
the features that you would want in a coding language, and so much more.
If you don’t want to get into a language that is too technical, but you do
want to make sure that you pick out a language that is able to handle a lot of
different programming tasks at the same time, then Python is the right
language for your needs.
You would want to go through and work with the Python language for many
reasons, especially when you are new to the world of coding. For those who
have never been able to do any coding in the past, you will find that the
Python coding adds in all of the ease of use that you need to see success
while still ensuring that you are going to be able to get all of the power that
you need actually to complete some of the coding that you would like.
Chapter 1 What is Python?
Disadvantages
• It is difficult to learn as it forces programmer to focus on
things that modern programming languages take care of
automatically
• The syntax, although it inspired a lot of other languages, is
very ugly.
• A lot of extraneous lines of codes are required even to perform
the most basic tasks.
Java Platform
Thanks to the millions of web applications developed using the language,
Java is possibly the most widely used programming language in the
world. Released as a core component of the Java platform in 1995 by Sun
Microsystems, it enabled applications built using Java to run on any
computer system that has Java Virtual Machine (JVM). Although it has a
syntax similar to C and C++ languages, it doesn’t demand low-level
considerations from the programmers. Oracle has acquired Sun
Microsystems and now manages Java platform.
For years, Microsoft’s C# and Sun’s Java remained in a cold war, each
trying to outdo the other programming language. Both languages were
heavily criticized for adding new features just to win a competition instead
of following a standard direction. It was not until 2004 that both languages
took to separate ways and developed into the unique languages as we know
them today.
Even then, Java remains the top programming language in the world and
Java platform runs on almost every laptop, game console, data center, and
even supercomputers.
Advantages
• Java frees the programmer from computer dependencies and
offers a vast degree of freedom
• Java is compatible with almost all computer systems. It means
almost every program created using Java language will run on all
those systems without any issues.
Disadvantages
• There have been serious security issues with Java over the
years. Severe security vulnerabilities were found in the last Java
version and Oracle advised every Java user to update to the latest
version.
• Java programs are known to be slower than the competition
even though there have been huge performance improvements in
recent versions.
• For a long time Java remained a proprietary platform. Even
after Sun declared it open-source, a long copyright battle ensued
between Oracle and Google over the use of Java in Google’s
Android.
Python is Different
We have briefly tackled the best options we have if we don’t want to use
Python. They are great options but before you jump ship, let me tell you
why I chose Python over others.
• Python is one of the easiest high-level programming
languages to learn. It means the time it takes from setup to
coding programs is very short.
• Code written in Python is easier to understand. It enables
programmers to consult codes written by other programmers to
adapt for their project.
• Python is an interpreter language. Code is executed one line at
a time which makes debugging easier for beginners.
• Python code can run on any computer no matter if it’s
Windows, Linux, UNIS, or a macOS based system.
• Python has a vast standard library that provides methods for
unique project requirements.
• Python supports various coding paradigms including Object
Oriented Programming (OOP) and functional programming.
• Python programming language is free and open source. This
has helped create an active programmer community and detailed
tutorials are available for free on the Internet.
• The open source nature of the language has also enabled many
programmers to extend Python capabilities by writing special
libraries. These libraries are available on the Internet free of
charge for everyone’s use.
• It’s very easy to create Graphical User Interface (GUI)
through Python.
• One of the biggest advantages of Python is its ability to
integrate with different programming languages. You can import a
specific library and start coding in a completely different language
and Python will understand the codes. Python supports extended
integration with C++ and Java. Not only that, Python code can be
placed inside a code written with another programming language.
These are the general advantages of Python over other programming
languages. Depending upon your project, Python might be able to provide
even more benefits. We are going to see how Python makes data analysis
easy.
Advantages of Using Python in Data Analysis
Strong with Strings
Python has a special place for strings. There are multiple string related
operations supported by Python. These operations are a big help in data
analysis stages of parsing and processing if you are dealing with string
data.
Dedicated Libraries
There are dedicated libraries in Python that help make data analysis projects
easier to handle. The libraries are regularly updated which means they are
compatible with the latest analysis algorithms.
Some of the popular data analysis libraries available on Python are:
o code in Python, you must have the Python Interpreter installed in your
computer. You must also have a text editor in which you will be writing and
saving your Python codes. The good thing with Python is that it can run on
various platforms like Windows, Linux, and Mac OS. Most of the current
versions of these operating systems come installed with Python. You can
check whether Python has been installed on your operating system by
running this command on the terminal or operating system console:
Python
Type the above command on the terminal of your operating system then hit
the Enter/Return key.
The command should return the version of Python installed on your system.
If Python is not installed, you will be informed that the command is not
recognized; hence you have to install Python.
Choosing a Python Version
The main two versions of Python are 2.x and 3.x. Python 3.x is obviously
the latest one but Python 2.x as of today is most likely still the most used
one. Python 3.x is however growing much faster in terms of adoption.
Python 2.x is still in use in many software companies. More and more
enterprises however are moving to Python 3.x. There are several technical
differences between the 2 versions. We can summarize in very a simple way
as Python 2.x is legacy and Python 3.x is the future. The advice for you is to
go for the latest version Python 3.x. From 2020 Python 2.x is not be
supported anymore.
Installation on Windows
To install Python on Windows, download Python from its official website
then double click the downloaded setup package to launch the installation.
You can download the package by clicking this link:
https://www.python.org/downloads/windows/
It will be good for you to download and install the latest package of Python
as you will be able to enjoy using the latest Python packages. After
downloading the package, double click on it and you will be guided through
on-screen instructions on how to install Python on your Windows OS.
Installation on Mac OS
To install Python in Mac OS, you must first download the package. You can
find it by opening the following link on your web browser:
https://www.python.org/downloads/mac-osx/
After the setup has been downloaded, double click it to launch the
installation. You will be presented with on screen instructions that will
guide through the installation process. Lastly, you will have Python running
on your Mac OS system.
Running Programs
One can run Python programs in two main ways:
• Interactive interpreter
• Script from command line
Here, you can write and run your Python scripts directly. To write the
“Hello” example, type the following on the interpreter terminal:
print("Hello")
Hit the enter/return key and the text “Hello” will be printed on the
interpreter:
Script from Command Line
This method involves writing Python programs in a file, then invoking the
Python interpreter to work on the file. Files with Python should be saved
with a .py extension. This is a designation to signify that it is a Python file.
For example, script.py, myscript.py, etc. After writing your code in the file
and saving with the name “mycode.py”, you can open the operating system
command line and invoke the Python interpreter to work on the file. For
example, you can run this command on the command line to execute the
code on the file mycode.py:
python mycode.py
The Python interpreter will work on the file and print the results on the
terminal.
very program has certain data that allows it to function and operate in the
way we want. The data can be a text, a number, or any other thing in
between. Whether complex in nature or as simple as you like, these data
types are the cogs in a machine that allow the rest of the mechanism to
connect and work.
Python is a host to a few data types and, unlike its competitors, it does not
deal with an extensive range of things. That is good because we have less to
worry about and yet achieve accurate results despite the lapse. Python was
created to make our lives, as programmers, a lot easier.
Strings
In Python, and other programming languages, any text value that we may
use, such as names, places, sentences, they are all referred to as strings. A
string is a collection of characters, not words or letters, which is marked by
the use of single or double quotation marks.
To display a string, use the print command, open up a parenthesis, put in a
quotation mark, and write anything. Once done, we generally end the
quotation marks and close the bracket.
Numeric Data Type
Just as the number suggests, Python is able to recognize numbers rather
well. The numbers are divided into two pairs:
Variables
You have the passengers, but you do not have a mode of commuting; they
will have nowhere to go. These passengers would just be folks standing
around, waiting for some kind of transportation to pick them up. Similarly,
data types cannot function alone. They need to be ‘stored’ in these vehicles,
which can take them places. These special vehicles, or as we programmers
refer to as containers, are called ‘variables,’ and they are exactly what
perform the magic for us.
Variables are specialized containers that store a specific value in them and
can then be accessed, called, modified, or even removed when the need
arises. Every variable that you may create will hold a specific type of data
in them. You cannot add more than one type of data within a variable.
In other programming languages, you will find that in order to create a
variable, you need to use the keyword ‘var’ followed by an equals mark ‘=’
and then the value. In Python, it is a lot easier, as shown below:
name = "John"
age = 33
weight = 131.50
is_married = True
In the above, we have created a variable named ‘name’ and given it a value
of characters. If you recall strings, we have used double quotation marks to
let the program know that this is a string.
We then created a variable called age. Here, we simply wrote 33, which is
an integer as there are no decimal figures following that. You do not need to
use quotation marks here at all.
Next, we created a variable ‘weight’ and assigned it a float value.
Finally, we created a variable called ‘is_married’ and assigned it a ‘True’
bool value. If you were to change the ‘T’ to ‘t’ the system will not
recognize it as a bool and will end up giving an error.
Focus on how we used the naming convention for the last variable. We will
be ensuring that our variables follow the same naming convention.
You can even create blank variables in case you feel like you may need
these at a later point in time or wish to initiate them at no value at the start
of the application. For variables with numeric values, you can create a
variable with a name of your choosing and assign it a value of zero.
Alternatively, you can create an empty string as well by using opening and
closing quotation marks only.
empty_variable1 = 0
empty_variable2 = ""
You do not have to name them like this necessarily; you can come up with
more meaningful names so that you and any other programmer who may
read your code would understand. I have given them these names to ensure
anyone can immediately understand their purpose.
Now we have learned how to create variables, let’s learn how to call them.
What’s the point of having these variables if we are never going to use
them, right?
Let’s create a new set of variables. Have a look here:
name = "Jonah"
age = 47
height_in_cm = 170
occupation = "Programmer"
I do encourage you to use your own values and play around with variables
if you like.
In order for us to call the name variable, we simply need to type the name
of the variable. In order to print that to the console, we will do this:
print(name)
Output
Jonah
The same goes for the age, the height variable, and occupation. But what if
we wanted to print them together and not separately?
Try running the code below and see what happens:
print(name age height_in_cm occupation)
Surprised? Did you end up with this?
print(name age height_in_cm occupation)
^
SyntaxError: invalid syntax
Process finished with exit code 1
Here is the reason why that happened. When you were using a single
variable, the program knew what variable that was. The minute you added a
second, a third, and a fourth variable, it tried to look for something that was
written in that manner. Since there wasn’t any, it returned with an error that
otherwise says:
“Umm… Are you sure, Sir? I tried looking everywhere, but I couldn’t find
this ‘name age height_in_cm occupation’ element anywhere.”
All you need to do is add a comma to act as a separator like so:
print(name, age, height_in_cm, occupation)
Output:
Jonah 47 170 Programmer
“Your variables, Sir!”
And now, it knew what we were talking about. The system recalled these
variables and was successfully able to show us what their values were. But
what happens if you try to add two strings together? What if you wish to
merge two separate strings and create a third-string as a result?
first_name = “John”
last_name = “Wick”
To join these two strings into one, we can use the ‘+’ sign. The resulting
string will now be called a String Object, and since this is Python we are
dealing with, everything within this language is considered as an object.
first_name = "John"
last_name = "Wick"
first_name + last_name
Here, we did not ask the program to print the two strings. If you wish to
print these two instead, simply add the print function and type in the string
variables with a + sign in the middle within parentheses. Sounds good, but
the result will not be quite what you expect:
first_name = "John"
last_name = "Wick"
print(first_name + last_name)
Output:
JohnWick
Why do you think that happened? Certainly, we did use a space between the
two variables. The problem is that the two strings have combined together,
quite literally here, and we did not provide a white space (blank space) after
John or before Wick; it will not include that. Even the white space can be a
part of a string. To test it out, add one character of space within the first line
of code by tapping on the friendly spacebar after John. Now try running the
same command again, and you should see “John Wick” as your result.
The process of merging two strings is called concatenation. While you can
concatenate as many strings as you like, you cannot concatenate a string
and an integer together. If you really need to do that, you will need to use
another technique first to convert the integer into a string and then
concatenate the same. To convert an integer, we use the str() function.
text1 = "Zero is equal to "
text2 = 0
print(text1 + str(text2))
Output:
Zero is equal to 0
Python reads the codes in a line-by-line method. First, it will read the first
line, then the second, then third, and so on. This means we can do a few
things beforehand as well, to save some time for ourselves.
text1 = "Zero is still equal to "
text2 = str(0)
print(text1 + text2)
Output:
Zero is still equal to 0
You may wish to remember this as we will be visiting the conversion of
values into strings a lot sooner than you might expect.
There is one more way through which you can print out both string
variables and numeric variables, all at the same time, without the need for
‘+’ signs or conversion. This way is called String Formatting. To create a
formatted string, we follow a simple process, as shown here:
print(f“ This is where {var 1} will be. Then {var 2}, then {var 3} and so
on”)
Var 1, 2, and 3 are variables. You can have as many as you like here. Notice
the importance of whitespace. Try not to use the spacebar as much. You
might struggle at the start but will eventually get the hang of it.
When we start the string, we place the character ‘f’ to let Python know that
this is a formatted string. Here, the curly brackets are performing a part of
placeholders. Within these curly brackets, you can recall your variables.
One set of curly brackets will be a placeholder for each variable that you
would like to call upon. To put this in practical terms, let’s look at an
example:
show = "GOT"
name1 = "Daenerys"
name2 = "Jon"
name3 = "Tyrion"
seasons = 8
print(f"The show called {show} had characters like {name1}, {name2} and
{name3} in all {seasons} seasons. ")
Output:
The show called GOT had characters like Daenerys, Jon, and Tyrion in all 8
seasons.
Chapter 5 How to Read Errors and Troubleshooting Your
Code
hese codes are great because they will save you a lot of time and will make
your code look nicer because you can reuse parts of your code without
tiring yourself out by having to rewrite it so many times. This is something
that you can do with object-oriented programming, or OOP, languages, a
category which Python is a part of. You can work with inheritances so you
can use a parent code and then make some adjustments to the parts of the
code that you want and make the code unique. As a beginner, you will find
that these inheritances can be quite easy to work with because you can get
the code to work the way you want it to work without having to write it out
a million times over.
To help you keep things simple and to understand how inheritances work a
little better, an inheritance is when you will take a ‘parent’ code and copy it
down into a ‘child’ code. You will then be able to work on the child code
and make some adjustments without having to make any changes in the
parent part of the code. You can do this one time and stop there, or you can
keep on going down the line and change the child code at each level
without making any changes to the parent code.
Working with inheritances can be a fun part of making your own code, and
you can make it look so much nicer without all that mess.
Overloading
Another process that you may want to consider when you’re working with
inheritances is learning how to ‘overload.’ When you work on the process
known as overloading, you can take one of the identifiers that you are
working with and then use that to define at least two methods, if not more.
For the most part, there will only be two methods that are inside of each
class, but sometimes this number will be higher. The two methods should
be inside the exact same class, but they need to have different parameters so
that they can be kept separate in this process. You will find that it is a good
idea to use this method when you want the two matched methods to do the
same tasks, but you would like them to do that task while having different
parameters.
This is not something that is common to work with, and as a beginner, you
will have very little need to use this since many experts don’t actually use it
either. But it is still something that you may want to spend your time
learning about just in case you do need to use it inside of your code. There
are some extra modules available for you that you can download so you can
make sure that overloading will work for you.
Final Notes about Inheritances
As you are working on your codes, you will find that it is possible that you
could work on more than one inheritance code. If you are doing this, it
means that you can make a line of inheritances that are similar to each
other, but you can also make some changes to them as well if needed. You
will notice that multiple inheritances are not all that different from what you
did with a normal inheritance. Instead, you are just adding more steps and
continuously repeating yourself so you can make the changes that you
want.
When you want to work with multiple inheritances, you have to take one
class and then give it two or more parent classes to get it started. This is
important once you are ready to write your own code, but you can also use
the inheritances to make sure the code looks nice as you write it out.
Now, as a beginner, you may be worried that working with these multiple
inheritances might be difficult because it sounds too complicated. When
you are working with these types of inheritances, you will create a new
class, which we will call Class3, and you will find that this class was
created from the features that were inside of Class2. Then you can go back
a bit further and will find that Class2 was created with the features that
come from Class1 and so on and so forth. Each layer will contain features
from the class that was ahead of it, and you can really go down as far as you
would like. You can have ten of these classes if you would like, with
features from the past parent class in each one, as long as it works inside of
your code.
One of the things that you should remember when you’re creating new code
and if you are considering to add in some multiple inheritances is that the
Python language will not allow you to create a circular inheritance. You can
add in as many parent classes as you want, but you are not allowed to go
into the code and make the parent class go in a circle, or the program will
get mad at you if you do so. Expanding out the example that we did above
to make another class or more is fine, but you must make sure that you are
copying the codes out properly before you even make changes so you can
get this program to work.
As you start to write out some more codes using the Python programming
language, you will find that working with different types of inheritances is
actually pretty popular. There are many times when you can just stick with
the same block of code in the program and then make some changes
without having to waste your time and tire yourself out by rewriting the
code over and over again.
Chapter 6 Variables
Creating a Variable
t is very easy to create a variable in Python. The assignment operator “=” is
used for this purpose. The value to the left of the assignment operator is the
variable identifier or name of the variable. The value to the right of the
operator is the value assigned to the variable. Take a look at the following
code snippet.
Name = ‘Mike’ # A string variable
Age = 15 # An integer variable
Score = 102.5 # A floating type variable
Pass = True # A Boolean variable
In the script above we created four different types of variables. You can see
that we did not specify the type of variable with the variable name. For
instance we did not write “string Name” or “int Age”. We only wrote the
variable name. This is because Python is a loosely typed language.
Depending upon the value being stored in a variable, Python assigns type to
the variable at runtime. For instance when Python interpreter interprets the
line “Age = 15”, it checks the type of the value which is integer in this case.
Hence, Python understands that Age is an integer type variable.
To check type of a variable, pass the variable name to “type” function as
shown below: type( Age)
You will see that the above script, when run, prints “int” in the output which
is basically the type of Age variables
Python allows multiple assignment which means that you can assign one
value to multiple variables at the same time. Take a look at the following
script:
Age = Number = Point = 20 #Multiple Assignment
print (Age)
print (Number)
print (Point)
In the script above, integer 20 is assigned to three variables: Age, Number
and Point. If you print the value of these three variables, you will see 20
thrice in the output.
For any programming language, the basic part is to store the data in
memory and process it. No matter what kind of operation we are going to
perform, we must have the object of operation. It is difficult for a skillful
woman to cook without rice. In Python language, constants and variables
are the main ones. In fact, both of them are identification codes used by
program designers to access data contents in memory.
The biggest difference between the two is that the contents of variables will
change with the execution of the program, while the contents of constants
are fixed forever. In the process of program execution, it is often necessary
to store or use some data. For example, if you want to write a program to
calculate the mid-term exam results, you must first input the students'
results, and then output the total score, average score and ranking after
calculation. This part describes how to store and access this data.
Variable Naming and Assignment
In a program, program statements or instructions tell the computer which
Data to access and execute step by step according to the instructions in the
program statements. These data may be words or numbers. What we call
variable is the most basic role in a programming language, that is, a named
memory unit allocated by the compiler in programming to store changeable
data contents. The computer will store it in "memory" and take it out for use
when necessary. In order to facilitate identification, it must be given a
name. We call such an object "variable." 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.
Useful methods
There are a few useful methods that you can use with dictionaries. These
methods are particularly useful when combined with loops. All of the
following methods need to be used by adding a dot notation after the name
of the variable followed by a parenthesis.
The first method is the keys(), which will output the keys to a dictionary.
The next method is the value(), which will output the values of keys. The
last method is the items() which will output both the keys and values
between parenthesis and separated by a comma.
Try out the example below.
1. flat = {'rooms': '2', 'bathrooms': '1', 'floor': '3rd', 'apartment': '306'}
2. print(flat.keys())
3. print(flat.values())
4. print(flat.items())
Program output:
C:\Users\...\PycharmProjects\GettingStarted\venv\Scripts\Python.exe
C:/Users/…/PycharmProjects/GettingStarted/MyFirstProgram.py
dict_keys(['rooms', 'bathrooms', 'floor', 'apartment'])
dict_values(['2', '1', '3rd', '306'])
dict_items([('rooms', '2'), ('bathrooms', '1'), ('floor', '3rd'), ('apartment',
'306')])
Process finished with exit code 0
Parameters
Now let’s explore how to add parameters to our functions. In many cases,
we need to take information from the user or elsewhere and use it inside of
a function. This technique is used by all programmers, regardless of what
kind of program they are creating. Follow the instructions below to see how
it works.
1. def greetUser(userName): # This is the parameter that we pass when
the function is called on lines 7 and 8.
2. purpose = input('State your purpose: ')
3. print(f'Hello {userName.title()}, are these your intentions: "
{purpose}" ?')
# Here we are using the parameter.
# We are also using the title method, to avoid any user error.
4.
5.
6. print('You have reached the umbrella corporation website') # This is
the first thing that will run in the program.
7. greetUser("rEbEcEa") # Once you have added a parameter you need
to supply a value while calling the function.
8. greetUser("dr. Green") # Each time you call a function, the new
parameter is
passed.
Program output:
C:\Users\...\PycharmProjects\GettingStarted\venv\Scripts\Python.exe
C:/Users/…/PycharmProjects/GettingStarted/MyFirstProgram.py
You have reached the umbrella corporation website
State your purpose: I'm looking for Alice
Hello Rebecea, are these your intentions: "I'm looking for Alice”?
State your purpose: Create a virus!
Hello Dr. Green, are these your intentions: "Create a virus!”?
Process finished with exit code 0
Keyword Arguments
In most cases, you may be passing more than one parameter into your
program. In cases like these you need to pass the value of these parameters
with respect to how they were defined in the function. Let’s see an example.
1. def greetUser(firstName, lastName):
2. purpose = input('State your purpose: ')
3. print(f'Hello {firstName.title()} {lastName.title()}, are these your
intentions: "{purpose}" ?')
4.
5.
6. print('You have reached the umbrella corporation website')
7. greetUser("rebecca", "chambers") # In this function call we have the
first name as the first parameter.
8. greetUser('chambers', 'rebecca') # In this function call we have the
last name as the first parameter
Program output:
C:\Users\...\PycharmProjects\GettingStarted\venv\Scripts\Python.exe
C:/Users/…/PycharmProjects/GettingStarted/MyFirstProgram.py
You have reached the umbrella corporation website
State your purpose: Rescue Alice
Hello Rebecca Chambers, are these your intentions: "Rescue Alice”?
State your purpose: Rescue Alice
Hello Chambers Rebecca, are these your intentions: "Rescue Alice”?
Process finished with exit code 0
In rare cases, a programmer will need to pass parameters out of order.
Although this is not always recommended, there are cases where it is
necessary. To do that, all you have to do is add the parameter name while
calling the function. Let’s take a look at the next example.
1. def greetUser(firstName, lastName):
2. purpose = input('State your purpose: ')
3. print(f'Hello {firstName.title()} {lastName.title()}, are these your
intentions: "{purpose}" ?')
4.
5.
6. print('You have reached the umbrella corporation website')
7. greetUser("rebecca", "chambers") # In this function call, we have the
first name as the first parameter.
8. greetUser('chambers', 'rebecca') # In this function call, we have the
last name as the first parameter
9. greetUser(lastName = 'chambers', firstName='Rebecca') # We
swapped the order and still were able to pass the
parameters as desired.
Program output:
C:\Users\...\PycharmProjects\GettingStarted\venv\Scripts\Python.exe
C:/Users/…/PycharmProjects/GettingStarted/MyFirstProgram.py
You have reached the umbrella corporation website
State your purpose: Saving Alice
Hello Rebecca Chambers, are these your intentions: "Saving Alice" ?
State your purpose: Saving Alice
Hello Chambers Rebecca, are these your intentions: "Saving Alice" ?
State your purpose: Saving Alice
Hello Rebecca Chambers, are these your intentions: "Saving Alice" ?
Process finished with exit code 0
Return Values
There are many cases where you will take a piece of information from the
user, run a function and need to return that value to the user again. It is very
simply done by writing ‘return’ in front of the variables you wish to return.
In this next example, we are going to create a very simple function that will
calculate the square of any number and return the value to the user.
1. def squareNum(numA): # Parameter
2. return numA *numA # Add the return at the beginning or else, by
default, it will return none.
3.
4. print(squareNum(3)) # Note that the function was called as an
argument and it can also be saved into a variable if necessary.
Program output:
C:\Users\...\PycharmProjects\GettingStarted\venv\Scripts\Python.exe
C:/Users/…/PycharmProjects/GettingStarted/MyFirstProgram.py
9
Process finished with exit code 0
Chapter 10 User’s Input and Loop
ython programming, like all other types of coding, is intended to solve the
problems that end users face. To do that, you need to get additional
information from the end user. For example, if someone needs to check if
he is eligible to play on the basketball team or if he is qualified to vote in
the elections, you can create a program that can give him the correct answer
he needs.
In this type of program, we need to know the age of the user before we give
an answer, which means that we have to build an interface that asks for an
answer from the user regarding his or his age. The user will enter his or her
age into the program using the input () method. Once he or she reaches age,
they can know the answer.
The input () method
The input () method is actually a stop for Python programs because it waits
for the user to fill in the program with some text. Once the Python program
has received the user's input, it can store the same in some kind mostof
variable that you create yourself. This makes programming and operation
easy. I have created a program that repeats the information you enter in the
shell prompt. It is interesting. Let's check it out.
message = input ("This program repeats everything you write. Just like a
parrot:")
print (message)
= RESTART: C: / Users / saifia-computers / Desktop / Python.py
This program repeats everything you write. Like a parrot: Terminator has
been destroyed.
Terminator has been destroyed.
>>> Sam
Retrace (most recent call last)
File "<pyshell # 136>", line 1, in <module>
Sam
NameError: name 'Sam' is not defined
>>>
= RESTART: C: / Users / saifia-computers / Desktop / Python.py
>>>
This program repeats everything you write. Just like a parrot: I have been
selected for the basketball team.
I have been selected on the basketball team.
>>>
You can see that the program returns whatever you say to it. The second
attempt gave an error because I did not run the program again. This means
that you have to run the program from the beginning every time you want to
run it.
The program took an argument from the user. It was a kind of instruction
that the adhering program used exactly the same wording as the user
entered. The prompt asks users to enter the information they want to display
in the shell. When the user presses enter, he executes the instructions.
You should write a clean code to make it easier for users to understand and
act on the instructions. The prompt should be clear and easy to follow so
that the user knows what to do. Let's write another program with the input ()
method.
qualification = input ("Enter your name and educational qualification:")
print ("Your information:" + qualification + "!")
= RESTART: C: / Users / saifia-computers / Desktop / Python.py
Enter your name and teaching qualification: John, MA (English literature)
Your data: John, MA (English literature)!
>>>
If you want to write a longer code that spans multiple lines, you can do that
with the input () function in Python. For example, if you want to let the user
know why you need a certain type of information, you can add an extra line
in the code. This code is longer than one line. This is useful because users
cannot easily enter the program with their personal information if you do
not tell them why you need a piece of information in the first place. To
achieve this goal, you can add the prompt within a variable and then pass
the variable to the input () function.
prompt = "We need your information to provide you with a custom job
search."
prompt + = "\ nEnter your name and educational qualification:"
qualification = input (prompt)
print ("Your information:" + qualification + "!")
= RESTART: C: / Users / saifia-computers / Desktop / Python.py
We need your data to let you search for a tailor-made job.
Enter your name and teaching qualification: Mazhar, MSc (Computer
Science)
Your data: Mazhar, MSc (Computer Science)!
>>>
Let's dig deeper into how the input () function works. When entering
information in the input () function, Python interprets it as a string. Let's see
how to enter numeric numbers. For example, you require the age of the user
to put in the record so you can do that with the following method.
user_age = input ("what is your legal age?")
= RESTART: C: / Users / saifia-computers / Desktop / Python.py
>>>
what is your legal age? 23
>>> user_age
'23'
>>>
= RESTART: C: / Users / saifia-computers / Desktop / Python.py
what is your legal age? 54
>>> user_age
'54'
>>>
The user's age information has been successfully stored in the variable
called user_age. When we ask Python to return the number, it returns in
quotes, meaning it is interpreted as a string. If you want to use the same as a
number, an error is displayed.
= RESTART: C: / Users / saifia-computers / Desktop / Python.py
what is your legal age? 25
>>> user_age> = 25
Retrace (most recent call last)
File "<pyshell # 143>", line 1, in <module>
user_age> = 25
TypeError: '> =' not supported between instances of 'str' and 'int'
>>>
Python displays an error because it cannot compare a string to an integer.
This problem can be solved if you use the int () function in your code. It
teaches Python how to treat an input as a numeric value. It converts a string
representation of a given number into a numeric representation. You can tell
Python to interpret a number as it is and to perform the math function you
want. You can run a conditional test by Python to see if your age is greater
than or equal to 25 or not.
user_age = input ("what is your legal age?")
user_age = int (user_age)
if user_age> = 25:
print ("\ nYou are legally entitled to vote!")
different:
print ("\ nYou are not eligible to vote. Return to your home.")
= RESTART: C: / Users / saifia-computers / Desktop / Python.py
what is your legal age? 20
You are not eligible to vote. Please go back to your house.
>>>
= RESTART: C: / Users / saifia-computers / Desktop / Python.py
>>>
what is your legal age? 25
You are legally eligible to vote!
>>>
= RESTART: C: / Users / saifia-computers / Desktop / Python.py
what is your legal age? 24
You are not eligible to vote. Please go back to your house.
>>>
= RESTART: C: / Users / saifia-computers / Desktop / Python.py
what is your legal age? 30
You are legally eligible to vote!
>>>
You can see in the examples above that Python is fully competent in
recognizing the numbers. It calculated perfectly and answered my questions
when I entered different numbers in the program.
ometimes, you may need to run certain statements based on conditions. The
goal in control statements is to evaluate an expression or expressions, then
determine the action to perform depending on whether the expression is
TRUE or FALSE. There are numerous control statements supported in
Python:
If Statement
With this statement, the body of the code is only executed if the condition is
true. If false, then the statements after If block will be executed. It is a basic
conditional statement in Python.
Example:
#!/usr/bin/python3
ax = 7
bx = 13
if ax > bx:
print('ax is greater than bx')
The above code prints nothing. We defined variables ax and bx. We then
compare their values to check whether ax is greater than bx. This is false,
hence nothing happens. The > is “greater than” sign. Let us change it to >,
this symbol means: “less than sign”.
Let see how we can write:
#!/usr/bin/python3
ax = 7
bx = 13
if ax < bx:
print('ax is greater than bx')
This prints the following:
If-Else Statement
This statement helps us specify a statement to execute in case the If
expression is false. If the expression is true, the Ifblock is executed. If the
expression is false, the Else block will run. The two blocks cannot run at the
same time. It’s only one of that can run. It is an advanced If statement.
Example:
#!/usr/bin/python3
ax = 10
bx = 7
if ax > 30:
print('ax is greater than 30')
else:
print('ax isnt greater than 30')
nested else part and skip the entire nested part. The code
gives this result:
Chapter 13 File Management
Import Statement
A module is able to contain definitions of a function and even statements,
which can be executable. With this, it is possible to initialize a module since
they execute only when our module is on the import statement.
Modules are capable of importing other modules that is why people use to
put the import type statements at the beginning of each since with the
names of our imported modules, they will locate on a space named global;
function that modules have for importing.
With the help of the last example, we can manage to import the module
created earlier and use the functions that we defined there.
As you see in this example, we created the op variable, who takes the task
of storing a string, which will specify the option that the users choose.
Then, two variables would be initialized, a and b; they will store the value
of the operators we are going to use to perform the mathematical
operations.
Afterward, the result variable will store the value that the function
calculator returns, according to the operators and the type of operation that
the users want. The function calculator comes from the module that we
have imported.
When the Python interpreter finds the import statement, it imports the
module, as long as it is located on the full search path. The search path is
nothing but a list where all the directories that Python accesses before
importing any module are located.
Namespaces in Modules
As you know, modules are files. Python creates a module object in which
all the names that we assigned in that module-file will be contained. What
does that mean? This means that namespaces are just places where all the
names that later become attributes are created.
Errors
When working with files, we will have an optional string. That string will
specify the way about how we will handle the errors of coding that may
arise in our program.
Those errors can only be handled and managed on files .txt
Ignore_errors()= This control statement will ignore the comments that have
a wrong format.
Stric_errors()= This control statement will generate a subclass or an
UnicodeError error type in case that there is any kind of fail, mistake or
error at the code of the file we are working with.
Encoding
Now we'll talk about string encoding, which we often use when we're
working with data storage. But what are data storages? This is just to say
that they are the representation in characters of the coding; your system is
based on bits and bytes in one familiar character.
The string encoding is expressed in the following way:
Newline
When we talk about the newline mode we refer to the mode that controls
the functionalities of creating a new line, these can be: '\r', " ", none,'\n', and
'\r\n'.
Newline statements are universal, and newlines are universal and can be
seen as a way of interpreting the text sequences of our code.
1. The end-of-line sentence in UNIX: "\n".
2. The end-of-line sentence in Windows: "\r\n"?
3. The end-of-line sentence in Max OS: "\r".
Handling Files
Handling the File Not Found Exception Error
There will be times when you will encounter the FileNotFoundError.
Handling such error depends on your intent or purpose with regards to
opening the file. Here are common reasons you will encounter this error:
Xlsx files
These files are those that allow us to work in spreadsheets as if we were
working in a windows Excel program; if our operating system is windows,
these files will have a much smaller weight to a file of type xlsx in another
operating system.
This type of file is beneficial when we work with databases, numerical
calculations, graphics and any other type of automation.
To start working with this type of file, we will have to install the necessary
library and this is done through the command "pip3 install openpyxl" in the
Python terminal.
Once our command has been executed, the openpyxl module will be
installed in our Python file.
Now we will create our first xlsx file:
In this example we can see that we have created our file by importing the
workbook function, which belongs to the openpyxl module, then we have
added our parameters such as: "wb" assigning the workbook function and
declaring that it will be our working document, then we add the name and
save the file.
Add information to the file with the xlsx module:
To add information to our file, we will rely on the append function
Now, to our document docxlsx.xlsx, we have added a tuple that contains
words like Python, document. Once we have created this, the append
function will allow us to add the information contained in the tuple in a
message.
Here we can see that the main function of append() is to admit iterable data
such as tuples.
Read documents in xlsx:
To read an xlsx file, we will only need to import the load_workbook class
and know the name of the file we are going to work with. It is also very
important that the files are in the same folder in which the program is
stored; otherwise, an automatic error will be generated.
Once this is done, we will specify the object to work with, and we will ask
for the information we need to read in order to print and compile it finally.
e are going to look at some of the tips and tricks that will help you to get
started with Python, along with how we can work with web scraping and
debugging some of our programs as well.
Let’s get started with this one to help us get started and finalize how good
our codes can be.
Web Scraping
Imagine for a moment that we are going to pull up a large amount of data
from many websites, and we want to be able to do this at a very fast rate.
How would we be able to go through this without having to manually go
through each of the websites that we have and gathering the data in this
manner?
This is where the process of web scraping is going to come into play.
Web scraping is going to be used by companies in order to collect a large
amount of information form websites.
But why does someone want to go through and collect all of this data, in
such large amounts, from these websites in the first place?
There are a lot of reasons for this, and some of them are going to include
the following:
Find the URL that you would like to scrape in the first place.
Inspect the page that you are planning on using.
Find the data that is on the page that you would like to extract.
Write out the code that you would like to use with the help of
Python in order to complete this process.
Run the code that you just wrote and then extract out the data
that you would like to use.
Store the data in the format that would be the most helpful for
you in the process.
There are also a few options that you are able to use when it is time to work
on the process of web scraping.
As we know, Python is already able to be used for a lot of different types of
applications, and there are going to be a ton of libraries with Python that is
going to be used for different purposes.
There are a few libraries that work the best when it comes to working with
the process of data web scraping will include:
n this part, we will discuss many things that you can do in Python. Some of
the things we can do in Python include the comments, reading and writing,
files and integers, strings, and variables. We are sure that after reading this,
you will be able to create the program that will run effectively. Due to the
interactive and descriptive nature of the Python, a beginner can handle
many things using it. Therefore, we will discuss some aspects and
comments in Python to help you get started. You can make amazing codes
in a short time using the Python programming language.
Comment
A comment, in the Python programming, starts with the # sign. This
continues until the programmer gets to the end of the line. A good example
is;
# This is a comment
Print (hello, thanks for contacting us)
It instructs your computer to print “hello, thanks for contacting us”. In fact,
the Python interpreter ignores all the comments. As a programmer,
however, you should not leave a comment after every line. You can put in a
comment when you need to explain something. Since long comments are
not supported by Python, it is important to use short and descriptive
comments to avoid them going across the lines.
Files
Apart from using the print function to obtain a string when printing on the
screen, it can be used to write something onto the file. First, you will have
to open up the myfile.txt and write on it before assigning it the myfile
which is a variable. Once you have completed the first step, you will have
to assign “w” in the new line to tell the program that you will only write or
make changes after the file has opened. It is not mandatory to use print
function; just use the right methods like read method.
Read method is used to open specific files to help you read the available
data. You can use this option to open a specific file. Generally, the read
method helps the programmers to read the contents into variable data,
making it easy for them to open the program they would like to read.
Integers
Always make sure that the integers are kept as whole numbers if you are
using them. They can be negative or positive only if there are no decimals.
However, if your number has a decimal point, use it as a floating number.
Python will automatically display such integers in the screen.
Moreover, you cannot place one number next to others if you are using the
integers because Python is a strongly typed language; thus it will not
recognize them when you use them together. However, you put both the
number and the string together by making sure you turn the number into a
string first before going to the next steps.
Triple Quotes
After reading and understanding both the single and double quotes, it is
now a time to look at the triple quotes. The triple quotes are used to define
the literal that spans many lines. You can use three singles, double, or single
when defining an authentic.
Strings
Although a string is seen as a complicated thing to many beginners, it is a
term used by the programmers when referring to a sequence of characters
and works just like a list. A string contains more functionality which is
specific than a list. You will find it challenging to format the strings when
writing out the code because some messages will not be fixed easily due to
its functionality. String formatting is the only way to go away within such a
situation.
Escape Sequences
They are used to donate special characters which are hard to type on the
keyboard or those that can be reserved to avoid confusion that may occur in
programming.
Operator Precedence
It will help you to track what you are doing in Python. In fact, it makes
things easy when ordering the operation to receive the right information.
So, take enough time to understand how the operator precedence works to
avoid confusion.
Variables
Variables refer to the labels donated somewhere in the computer memory to
store something like holding values and numbers. In the programming
typed statistically, the variables have predetermined values. However,
Python enables you to use one variable to store many different types. For
example, in the calculator, variables are like memory function to hold
values which can be retrieved in case you need them later. The variables
can only be erased if you store them in the newer value. You will have to
name the variable and ensure it has an integer value.
Moreover, the programmer can define a variable in Python by providing the
label value. For instance, a programmer can name a variable count and even
make it an integer of one, and this can be written as; count=1. It allows you
to assign the same name to the variable, and in fact, the Python interpreter
cannot read through the information if you are trying to access values in the
undefined variable. It will display a message showing syntax error. Also,
Python provides you with the opportunity of defining different variables in
one line even though this not a good according to our experience.
n this part, we’ll discuss working with files. Often during your
programming journey, you'll want to pull in data from external files and
manipulate that data. For example, maybe you have a large word document,
but you only want sentences that contain certain words and phrases. With
Python, you can read the document, do a search for the desired strings, join
these strings into a list, and write a new document containing just the target
strings. Python has many built-in functions and features that make loading,
reading, and even writing to external files simple. Let’s see the various
ways we can interact with a file using Python.
Opening and Reading
To begin our exploration of files, we’ll first need a text file to work with.
Copy any text you’d like into a text editor and save it to the same directory
as your Python scripts, saving it with the “.txt” format. If you need text to
work with, you can try writing the following and running the script:
import this
Running this script will activate a Python Easter Egg, printing out the Zen
of Python (a list of the principles that guide design in Python). If you would
like, you can copy that text into a text file and save it.
To open a file in Python, we can use the open() function, which takes two
arguments. The first argument is the file that you want to open, while the
second argument specifies the mode that the file will be opened in. For
instance, if you have a folder called “Projects” on your C drive, you would
have to specify that Python looks for the targeted file by passing in:
C:\\Projects\\test_text.txt.
With this in mind, you can assign the contents of a file to a variable by
doing this:
text_file = open("text_test.txt", "r")
The first argument specifies where Python should look for the file that you
want to open. If the file is in the same directory as the program you are
writing, all you need to do is provide the name and extension of the file. If
this isn’t the case and the file is located elsewhere, you’ll need to provide
the full path to the file, as mentioned above.
In the case above, the r specifies that we want to open the document in
read-only mode. The other file-handling options include:
w mode - Specifies you want to open the file in write-only mode.
w will create the file that has been passed in as the first argument if the file
doesn’t already exist. Be careful when using this, because the data in the
file will be erased if the file already exists.
a mode – Used for opening the file in appending-mode. Appending is for
adding text to the current body of the file. If the file doesn’t exist yet, the
file will be created. Unlike w, the existing data in the file isn’t erased if the
file already exists. This is because any new data is added to the end of the
file.
r+ - Specifies that you want to both read and write to the file.
After you have created a file object by using the open() function and the
assignment operator, it’s possible to read out individual lines in the
document by using the readline() function, which is done by using dot
notation on the file object:
text_file.readline()
Each time the readline() function is called, it moves to the next line in the
text document. This means that if you call the function and print the results
three times, Python will print out the first three lines in the document.
A more efficient way of printing out multiple lines from a file is by using a
for loop. We can easily print out all the lines in a text file by writing a
statement like:
for i in text_file:
print(i)
Now that you know how to open files in Python, you should also know how
to close them. You can close a file you’ve opened simply by using the
close() function on it, like this:
text_file.close()
You should get in the habit of closing files after you are done working with
them, because this frees up resources your system is using to keep the file
open.
ow that you know the basics behind Python programming, you might be
wondering where exactly could you apply your knowledge. Keep in mind
that you only started your journey, so right now, you should focus on
practicing all the concepts and techniques you learned. However, having a
specific goal in mind can be extremely helpful and motivating.
As mentioned earlier, Python is a powerful and versatile language with
many practical applications. It is used in many fields, from robotics to game
development and web-based application design. In this part, you are going
to explore some of these fields to give you an idea about what you can do
with your newly acquired skills.
Machine Learning
You’ve probably heard about machine learning because it is the new
popular kid on the block that every tech company relies on for something.
Machine learning is all about teaching computer programs to learn from
experience based on data you already have. Thanks to this concept,
computers can learn how to predict various actions and results.
Some of the most popular machine learning examples can be found in:
Cybersecurity
Data security is one of the biggest concerns of our century. By integrating
our lives and business into the digital world, we make it vulnerable to
unauthorized access. You probably read every month about some
governmental institution or company getting hacked or taken offline. Most
of these situations involve terrible security due to outdated systems and
working with antiquated programming languages.
Python's own popularity is something that makes it far more secure than
any other. How so? When something is popular, it becomes driven by a
large community of experts and testers. For this reason, Python is often
patched, and security issues are plugged in less than a day. This makes it a
popular language in the field of cybersecurity.
Web Development
As mentioned several times before, Python is simple yet powerful. Many
companies throughout the world, no matter the size, rely on Python to build
their applications, websites, and other tools. Even giants like Google and
Facebook rely on Python for many of their solutions.
The main advantages of working with Python so that we won't explore them
yet again. However, it is worth mentioning that Python is often used as a
glue language, especially in web development. Creating web tools always
involves several different programming languages, database management
languages, and so on. Python can act as the integration language by calling
C++ data types and combining them with other elements, for example. C++
is mentioned because in many tech areas, the critical performance
components are written in C++, which offers unmatched performance.
However, Python is used for high-level customization.
Conclusion
hank you for making it through to the end of Coding with Python: A Simple
and Straightforward Guide for Beginners to Learn in the Fast Way the
Programming with Python, 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 spend some time taking a look at some of the different
parts that we are able to focus on when it is time to work with coding our
own applications and more. Many people are worried about getting into
coding because they think that it is going to be too difficult for them to get
started, and they worry that they will never be able to handle all of the work
that is going to come with their coding needs.
And that is part of the beauty that is going to come with using the Python
language, and we hope that you are able to see this when it comes with this
kind of language and with the examples that are in this guidebook, you will
find that you will be able to work with the Python language. This is going
to be an easy language for beginners and advanced coders to work with, but
you will find that it has a lot of power behind it and will help you to get
some of the work done in coding that you would like.
This guidebook has spent some time looking at the benefits of working with
the Python language, and all of the different options that you are able to
work with when it comes time to work on your program. We spent some
time looking at how to write out some of our own conditional statements,
our loops, exceptions, inheritances, and so much more. We even spent some
time looking more in-depth about the work we can do with OOP languages
and the classes that we would like to work with, and this will ensure that we
can keep things as organized as possible within the code that we do.
When we are able to put all of these parts together inside of our work of
coding, you will find that it is a lot easier to work with some of the coding
that we want, even when we are a beginner. You will find that this is easier
to accomplish than you think, and we are able to make codes that work with
all sorts of projects. And considering that Python is going to work well with
a lot of the major companies out there and some of the platforms that they
want to use as well, including the Google search engine and some of the
functionality of the YouTube site, you can see why this is a language that
you are able to learn, and get a lot of use out of as well.
You no longer have to be worried or scared about working with a coding
language. While some of the coding languages in the past may have been a
bit difficult to work with and would not provide you with the results that
you wanted all of the time, you will find that Python is not going to come
with this kind of situation at all. You may have even glanced through some
of the different parts of this ahead of time and noticed that it is easy enough
to read some of these codes, before even starting. Take that as a confidence
boost, and see how easy working with this language can be.
There may be a lot of different coding languages that we are able to work
with when it comes to focusing on the coding that you would like to
accomplish. But Python keeps proving that it is one of the best options out
there for us to work with. When you are ready to learn more about coding
in Python and all of the neat things that we are able to do with it, make sure
to check out this guidebook and take a look at how great it can be.
SQL PROGRAMMING FOR BEGINNERS:
Eugene Gates
Introduction
SQL helps when you want to create tables based on the data you
have.
SQL can store the data that you collect.
SQL can look at your database and retrieves the information on
there.
SQL allows you to modify data.
SQL can take some of the structures in your database and change
them up.
SQL allows you to combine data.
SQL allows you to perform calculations.
SQL allows data protection.
Traditionally, many companies would choose to work with the ‘Database
Management System,’ or the DBMS to help them to keep organized and to
keep track of their customers and their products. This was the first option
that was on the market for this kind of organization, and it does work well.
But over the years there have been some newer methods that have changed
the way that companies can sort and hold their information. Even when it
comes to the most basic management system for data that you can choose,
you will see that there is a ton more power and security than you would
have found in the past.
Big companies will be responsible for holding onto a lot of data, and some
of this data will include personal information about their customers like
address, names, and credit card information. Because of the more complex
sort of information that these businesses need to store, a new ‘Relational
Database Management System’ has been created to help keep this
information safe in a way that the DBMS has not been able to.
Now, as a business owner, there are some different options that you can
pick from when you want to get a good database management system. Most
business owners like to go with SQL because it is one of the best options
out there. The SQL language is easy to use, was designed to work well with
businesses, and it will give you all the tools that you need to make sure that
your information is safe. Let’s take some more time to look at this SQL and
learn how to make it work for your business.
How This Works with Your Database
If you decide that SQL is the language that you will work on for managing
your database, you can take a look at the database. You will notice that
when you look at this, you are basically just looking at groups of
information. Some people will consider these to be organizational
mechanisms that will be used to store information that you, as the user, can
look at later on, and it can do this as effectively as possible. There are a ton
of things that SQL can help you with when it comes to managing your
database, and you will see some great results.
There are times when you are working on a project with your company, and
you may be working with some kind of database that is very similar to
SQL, and you may not even realize that you are doing this. For example,
one database that you commonly use is the phone book. This will contain a
ton of information about people in your area including their name, what
business they are in, their address, and their phone numbers. And all this
information is found in one place so you won't have to search all over to
find it.
This is kind of how the SQL database works as well. It will do this by
looking through the information that you have available through your
company database. It will sort through that information so that you are
better able to find what you need the most without making a mess or
wasting time.
Relational Databases
First, we need to take a look at the relational databases. This database is the
one that you will want to use when you want to work with databases that
are aggregated into logical units or other types of tables, and then these
tables have the ability to be interconnected inside of your database in a way
that will make sense depending on what you are looking for at the time.
These databases can also be good to use if you want to take in some
complex information, and then get the program to break it down into some
smaller pieces so that you can manage it a little bit better.
The relational databases are good ones to work with because they allow you
to grab on to all the information that you have stored for your business, and
then manipulate it in a way that makes it easier to use. You can take that
complex information and then break it up into a way that you and others are
more likely to understand. While you might be confused by all the
information and how to break it all up, the system would be able to go
through this and sort it the way that you need in no time. You are also able
to get some more security so that if you place personal information about
the customer into that database, you can keep it away from others, in other
words, it will be kept completely safe from people who would want to steal
it.
Client and Server Technology
In the past, if you were working with a computer for your business, you
were most likely using a mainframe computer. What this means is that the
machines were able to hold onto a large system, and this system would be
good at storing all the information that you need and for processing
options.
Now, these systems were able to work, and they got the job done for a very
long time. If your company uses these and this is what you are most
comfortable with using, it does get the work done. But there are some
options on the market that will do a better job. These options can be found
in the client-server system.
These systems will use some different processes to help you to get the
results that are needed. With this one, the main computer that you are using,
which would be called the ‘server,’ will be accessible to any user who is on
the network. Now, these users must have the right credentials to do this,
which helps to keep the system safe and secure. But if the user has the right
information and is on your network, they can reach the information without
a lot of trouble and barely any effort. The user can get the server from other
servers or from their desktop computer, and the user will then be known as
the ‘client’ so that the client and server are easily able to interact through
this database.
Table
Record/Tuple
Field/ Column
Instance
Schema
Keys
We will cover some of these components as we progress further into the SQL
lessons covered in the book. For now, let us look at tables and columns.
SQL Tables
Tables are objects used to store data in a Relational Database Management System.
Tables contain a group of related data entries with numeric columns and rows.
Tables are the simplest form of data storage for relational databases. They are also
a convenient representation of relations. However, a table can contain duplicate
rows while a relation cannot contain any duplicate. The following is an example of
a DVD rental database table:
The table shows information about customers in a DVD rental database.
SQL Fields
Tables break down further into smaller entities referred to as fields. Fields are
columns in tables designed to hold information about records in the specified table.
For example, in the table above, we can see fields that contain Customer_id,
store_id, first_name and last_name.
SQL Records
In a database, we use Records or Rows to refer to a single entry in a database table.
It represents a collection or related data. We can also regard it as the horizontal
entity in a database table. For example, in the above table, we have five records or
tuples.
SQL
Columns
In a database table, we use a column to refer to the vertical entity containing data
related to specific fields in a table. For example, in the above table, a column could
be first_name or last_name.
NULL Values
A null value is a value assigned to a blank field. This means that a field with a
value NULL has no value. In SQL, a zero or a space is not a NULL value. NULL
value mainly refers to a field that is blank in a record.
SQL Constraints
Constraints are rules applied to columns in a database table. We mainly use them to
govern the type of data stored within the table. This ensures that the database is
accurate and reliable thus minimizing errors.
We can set constraints on columnar or tabular level. Columnar level rules apply
only to the specified column while tabular level rules apply to the entire database
level.
SQL contains various rules applied to the stored data.
They include:
NOT NULL: This rule ensures that a table or column does not contain
null value, which means during record creation, you must enter either a
zero, Space, or another value
UNIQUE: Ensures each value is unique and no duplicates are available
DEFAULT: We use this constraint rule to set a default value for a
column where we have an unspecified value
PRIMARY KEY: Identifies each record distinctively in a table. We
create this rule by combining NOT NULL and UNIQUE constraints
FOREIGN KEY: We use this constraint to identify (distinctively) a
record in another database table
CHECK constraint: We use this constraint to confirm if the values in a
column fulfill defined conditions
INDEX constraint: We use this to create and retrieve data from a
database
Data Integrity
Data integrity refers to the consistency and accuracy of the data. When creating
databases, you MUST pay attention to data integrity. A good database must ensure
reinforcement of data integrity as much as possible. Data integrity must also remain
maintained during manipulation and update of the database.
Various factors can lead to compromised data integrity within a database. These
factors include:
Normalization
Normalization refers to the process of organizing databases to improve data
integrity and reduce data redundancy. This process aids the simplification of the
database design. Database normalization offers a range of advantages including:
Unnormalized Form
First Normal Form
Second Normal Form
Third Normal Form
Elementary-Key Normal Form
Boyce-Codd Normal Form
DBMS VS RDBMS
We have already covered RDBMS. DBMS is not different either. DBMS is a
software package we use to create and manipulate databases.
DBMS and RDBMS give programmers and users an organized way of working
with databases. DBMS and RDBMS are not very different since both provide a
physical database storage.
With the above noted, some relevant difference between them are worth
mentioning.
They include:
RDBMS DBMS
Supports Normalization Normalization is not available
in a DBMS
Supports Distributed Database Does not support Distributed
System Database System
Stores data in a table format Stores data is a normal
computer form
Integrity constraints are defined Security for data
for the purpose of ACID manipulation is not applied
property by DBMS
Can handle large amounts of Designed to small scale data
data such as a Company and personal use
database
It supports multiple users Supports a single user
Cases of data redundancy are Data redundancy is a very
close to none common scenario
Stores data in tabular form and Mainly stores data in
utilizes primary keys hierarchical or navigational
format
Requires complex software and Low software and hardware
high-performance hardware to requirements for
implement implementation
Supports client-server Client-side architectures is
architecture not supported
They include PostgreSQL, Include file system files, xml
MySQL and Oracle etc. files, and windows registry.
At this point in the guide, you know enough to start working with SQL and
databases.
Chapter 3 Data Types
Numeric strings
Character strings
Time and date values
A database user may have used this line to perform a search. The system
will evaluate this line for each data row. If NAME’s value is equal to
SMITH in one of the data rows, the search gives TRUE as the result.
Afterward, the user will get the data linked with that search result.
Chapter 4 Exploring a Database
database is properly organized and collected data that are stored and can be
accessed through electronic means from a particular computer. Formal
design and modeling methods are essential in developing a database. Before
a designer develops a database, his first assignment is to create a conceptual
data model that reflects the type of information to be kept in the database.
The database management system provides the access to the stored data.
The DBMS interacts with application users, and the database to analyze and
capture the stored data. It also allows end users have seamless interaction
with more than one database. Although there may be restrictions in
accessing some data, however this will be based on the security level made
by the programmer or database owner. The functions of a database are
diverse; it allows entry of information, storage of data and also retrieving
large files of information. Aside from doing all of these, it also provides
ways in which the data stored can be managed and organized effectively.
The Functions of a Database Management Systems
A database is known as the collection of data and a common example is a
spreadsheet or card index form. The DBMSs manages the data stored in the
below four categories.
Data Definition: Data definition consists of defining the structure of your
data, creation and modification of your data.
Update: After you have saved your data on your database, the DBMS gives
you the permission to insert new information, alter or modify the former
information, or even delete any of the information stored.
Retrieval: DBMS helps you provide information in a readable and usable
form. The stored data when retrieved may be available in the exact format it
was saved, or a new format.
Administration: For every data stored, there is an end-user, data and a
future need for the data. Every data stored needs to be secured properly, and
DBMS makes it easy for the application administrator to register and
monitor the data effectively, enforces data security to prevent unauthorized
personnel from accessing the data, to maintain the integrity and value of the
data without any corruption.
Benefits of Database
Database is helps to facilitate the development of a new application,
improves factors like data security, data access to enabled users, promotes
data integrity and also reduces data errors and redundancy.
Classification of Database
Database can be classified using the following criteria; type of the contents
stored, application area and technicality of the database, such as the
structure of the database. The classification you are about to read is made
based on database distribution, and there are four major distribution systems
for DBMS.
Centralized Systems: Databases that are stored in a single location so that
the data can be accessed and used by other systems are stored with a
centralized database system.
Distributed Database System: The actual databases in this system are
distributed evenly from different locations, which are connected to a
computer network.
Homogenous Distributed Database System: The same DBMS is used in
this database system, though they are from different location.
Heterogonous Distributed Database System: In this database system,
different DBMS are used by different sites, however there is a presence of
additional software to support easy exchange of data.
Types of Databases
The type of database you want is based on the usage requirements. You are
about to learn the available database in the market today.
Centralized database
Centralized database is abbreviated as CDB, it is a database that is stored,
located and maintained in a single location, and this location can be a
database system or in the central computer. Centralized database is often
used by organizations like a business company or a university.
The centralized database has a good number of advantages compared to
other types of databases. CBD maximizes the quality of a data properly,
helping the data to maintain its integrity, accuracy, and reliability. For the
fact that there is only one storage location, there is a higher level of security,
and better data preservation. Although CBD is easy to maintain and change
at any time, given it needs to be updated, yet it is highly dependent on
network connectivity.
The disadvantages of CBD are few, but they are however detrimental to the
organization. If for any reason the unexpected occurs, all data will be lost
and it may be difficult to retrieve the data, because it was saved in one
location.
Distributed database
When information is stored on multiple storage devices, or locations, it is
called distributed database. This information may be stored on difference
computers in the same physical place, but they are not stored on the same
processor. Distributed database can be subdivided into two groups namely,
homogenous database and heterogeneous database.
Distributed database involves two processes, the replication and
duplication.
Replication is the use of specific software that looks for changes in the
distributed database. The replication process is complex and time
consuming.
While duplication identifies one of the stored databases as the master and
duplicates what it does. However, both replication and duplication can keep
the integrity of the data in all distributed locations.
The distributed database should not be confused for centralized database.
Although the distributed database has a multiple storage location, it still
relies on the central DBMS which manages the storage devices remotely.
The benefits of having a distributed database will increase the reliability
and availability of your data, easy expansion improved performance and it
is also a mean of saving cost.
DBAs are very complex, which makes it a disadvantage because it needs
extra effort to ensure that all data are evenly distributed to all locations. It
also needs experienced hands to be able to manage the data, and provide
maximum security on the stored data.
Personal database
A personal database is a stored data on a personal computer, it is created to
be used, organized and managed by one person. It can be created by a
computer programming language like Practical Extraction and Reporting
Language (PERP). A personal database only support one application, makes
use of one computer.
End-user database
An end user is not usually concerned about the about the kind of
transactions and operations done, but it is only concerned about the
software or application. The end user database is specially meant for the
end user, who can be a manager who summarizes the collected information
in a database.
Commercial database
Commercial databases are information collected and presented
electronically, which are managed by commercial entities. These databases
are stored, and maintained for customers’ services, they are available to
customers for commercial purposes. There are 5 reliable sources where you
can access a commercial database; a commercial database retailer, internet
sources, library or places with site license, a help of a professional, and
personal subscription source.
Commercial databases have advantages and disadvantage, like every other
database.
The commercial database requires no physical space, since it is online,
unlike printed materials that need library or bookshelf. Aside from this part,
the database can be easily monitored, and can be accessed by multiple users
at the same time.
The disadvantages of commercial database are that it needs constant
network connectivity and cost of management can be expensive for both the
administrator and user.
NoSQL database
A NoSQL database was originally referred to as a non-relational database
or a non-SQL. It is used in managing big data, and real time web
applications. It is a database that is built to provide mechanism for retrieval
and storage of data that are modeled in other means used in such relational
database. There are different classifications, and sub-categories of NoSQL
database.
The output shows that the database was created successfully. However, it
will be good for you to confirm whether or not the database was created. To
do this, use the SHOW command as shown below:
SHOW databases;
The above output shows that the school database was created successfully.
The above command returns the list of databases you have in your system.
An attempt to create a database that already exists generates an error. To
confirm this, try to recreate the school database by running the following
command:
CREATE DATABASE school;
The above output shows an error because the database already exists. To
avoid this error, we can use the optional clause IF NOT EXISTS. This is
showed below:
RENAME Database
Sometimes, you may need changing the name of a database. This is after
you realize that the name you have given to the database is not much
relevant to it. You may also need giving the database a database name. This
can be done using the SQL RENAME DATABASE command.
The command takes the syntax given below:
RENAME DATABASE old_database_name TO new_database_name;
For example, in my case, I have the following list of databases:
Let us rename the database named movies by giving it the name movies_db.
This means we run the following command:
RENAME DATABASE movies TO movies_db;
The database should be renamed successfully.
Database Backup
It is always important to back up your database. This is because an
unexpected and unforeseen event may happen to the database. Examples of
such unforeseen events include Cyber-criminality and natural disasters. In
case of such an occurrence, it will be impossible for you to recover your
database if you had not backed it up. However, if your database had been
backed up, it will be easy to recover the database and resume normal
operations. You also need to back up your database to prevent the loss of
your data. SQL provides you with an easy way of creating a backup of your
database.
To create a database backup, you use the BACKUP DATABASE command.
This command takes the syntax given below:
BACKUP DATABASE database_name
TO DISK = 'file_path';
The database_name parameter denotes the name of the database you need to
back up. The file_path parameter denotes the file leading to the directory
where you need to back up your database. The above command should be
done when you need to back up the database from the beginning.
However, the differential command can be used if you need to create a
differential backup. When you do this, the backup will only be created from
the time you did your last full backup of the database. To do this, you must
change the command to:
BACKUP DATABASE database_name
TO DISK = 'file_path'
WITH DIFFERENTIAL;
We have changed the command by adding the WITH DIFFERENTIAL
statement. This means that the command will perform a differential backup
on the database.
Suppose we need to create a full backup of the database named school. We
will store the backup file in the local disk D.
The following command will help us accomplish this:
BACKUP DATABASE school
TO DISK = 'D:\schoolDB.bak';
If you need to create a differential backup of the database, just run the
following command:
BACKUP DATABASE school
TO DISK = 'D:\schoolDB.bak'
WITH DIFFERENTIAL;
We have just added the WITH DIFFERENTIAL statement to the command.
Note that with a differential backup, the backup will be created within a
short time. This is because you are only backing up changes that have
occurred within a short period. However, a full backup will take a longer
time to complete.
Creating Tables
To create a table, we have to define the table name, its column names and
their corresponding data types.
We create tables by running the CREATE TABLE command. The tables are
created within the database, meaning that one database can have many
tables. The tables hold the data. The table stores the data in the form of
rows and columns. The CREATE TABLE command takes the syntax given
below:
CREATE TABLE tableName (
column1_name datatype constraints,
column2_name datatype constraints,
....
);
To make it the above syntax easy to understand, we need to create a table
within the school database. Just run the following command from the
MySQL command line.
-- Syntax for MySQL Database
CREATE TABLE students (
regno INT NOT NULL PRIMARY KEY AUTO_INCREMENT
UNIQUE,
name VARCHAR(30) NOT NULL,
birth_date DATE,
age int NOT NULL
);
RENAME TABLE
Sometimes, you may need to change the name of your database table. This
could be after you realize that the current name of the table is not
meaningful. It then becomes necessary for you to change the name of the
table. This is possible by the use of the RENAME TABLE command. The
command takes the following syntax:
ALTER TABLE old_table_name
RENAME TO new_table_name;
;
For example, to change a table named employees to workers, we run the
following command:
ALTER TABLE employees
RENAME TO workers;
The table will be renamed successfully.
ALTER TABLE
This is the statement we use any time we need to change the columns of a
table. The modification in this can mean the need to add, change or delete a
table column. This command can also help you add or drop the various
constraints that may have been imposed on an existing table.
Adding a Column
To add a new column to a table, use the ALTER TABLE command with the
following syntax:
ALTER TABLE tableName ADD columnName column-definition;
However, you may sometimes to add multiple columns to the table. In such
a case, use the command with the following syntax:
ALTER TABLE tableName
ADD (column1 column-definition,
column2 column-definition,
.....
column_n column-definition);
Let us show this with an example. Suppose we have the workers table with
the following columns:
We can describe the table to see whether or not the change was reflected:
Dropping Columns
Sometimes, you may need to reduce the number of columns you have in a
certain table. In such a case, it will be necessary for you to drop or delete
some table columns. It is possible with SQL.
To delete a table column, we combine the ALTER TABLE and the DROP
statements. This is done using the syntax given below:
ALTER TABLE tableName DROP COLUMN column_name;
Again, we will use the workers table to show how to use the above
command. The table has the following set of columns:
The above figure shows that the column deleted from the table successfully.
It is important to know the various data types supported in SQL. SQL data
types specify the data for every object. Every variable, column and
expression in SQL has an associated data type.
Chapter 6 Getting Started with Queries
Classification of Indexes
The data in the database page of SQL Server can be divided into two types
according to the storage structure: Clustered Index and Non clustered Index.
1. Cluster index
Cluster index (also called "clustered index") means that the physical storage
order of data rows in the table is the same as the index order. Cluster index
consists of upper and lower layers: the upper layer is an index page, which
contains index pages in the table and is used for data retrieval; The lower
layer is the data page, which contains the actual data page and stores the
data in the table.
When creating a clustered index in a column of a table, the data in the table
will be reordered according to the index order of the columns and the table
will be modified. Therefore, only one cluster index can be created in each
table. Cluster indexes are created on columns that are frequently searched
or accessed sequentially.
2. Non-cluster index
The non-clustered index (also called "non-clustered index") does not
change the physical storage location of the data rows in the table. Data is
stored separately from the index and is linked to the data in the table
through the pointer carried by the index. Non-clustered indexes are similar
to those in textbooks.
The data is present in one place, the index is present in another place, and
the index has a pointer to the storage location of the data. The items in the
index are stored in the order of index key values, while the information in
the table is stored in another order (non-clustered indexes can specify this).
A table can contain multiple non-clustered indexes, and a non-clustered
index can be created for each column commonly used when looking up data
in the table.
The method of creating a clustered index is similar to that of the non-cluster
index, both uses CREATE INDEX statement, except that the CLUSTERED
clause needs to be specified to create a clustered index.
hrough this part, when we bring up the topic of the operators that are inside
of the database, we are going to talk about the characters and the words that
we have reserved, and any that can be used along with the WHERE clause
of the statements we write. Operators are helpful because we are able to use
them to perform operations in the statements, such as comparisons and any
of the equations that we need in math, but they can also come in to make it
easier to set up some of the parameters that we want to see around our
statements. And we need always to remember that they are there to help us
connect together two or more parameters that we have in the same
statement if this is something that our code needs.
During this process, we are going to need to remember that there are a few
options of operators that you are able to use in these statements. The four
most common options that we are able to work with include:
Operators that are used to help negate conditions.
Logical operators
Comparison operators
Arithmetic operators.
Logical Operators
The first operator type that we are going to spend some time focusing on in
this guidebook will be the logical operators. These are going to be the kinds
of operators that we are able to use with the keywords of our statements,
and they are going to be easier to form with comparisons inside of the
statements. Some of the different logical operators that we are able to add
into our statements will include:
Addition—you will just need to use the “+” sign to get started on
using addition. For this example, we are going to add up the
values for the overhead column and the materials column. The
statement that works for this is:
SELECT MATERIALS + OVERHEAD FROM
PRODUCTION_COST_TBL.
Subtraction—you can also do some basic subtraction when it
comes to your SQL statements. You will simply need to use the
“-“ sign to do this.
Multiplication—it is possible to do multiplication from your
tables as well. You would need to use the “*” sign to do this.
Division—this one will just need the “/” sign to get started.
With the arithmetic operators, you will be able to gain a lot of freedom in
some of the codes that you are writing. You can combine a few of these
operators together and even end up with your own equation inside of the
statement. For example, you could have one statement with a bit of
multiplication along with some division and addition if you would like. You
can also have it so that you are just using a few multiplication signs in the
same statement as well. Whatever is needed to bring the code together and
make it work in the way that you want is available when it comes to these
arithmetic operators.
One thing that we need to remember when we decide to add in more than
one of these operators to our statement at a time is that we need to work
with something known as the principles of precedence to make sure that we
get it right. This means that the syntax is going to be able to take care of the
arithmetic operators in a certain way to help us get the right answer.
When we are doing this kind of principle in SQL, the syntax is going to
take care of everything that we need to multiply first, and then it will pay
attention to everything that we need to divide, and then it will do those that
should be added together, before finishing up with the things that should be
subtracted from one another. And the syntax is going to do this in a manner
that goes from left to right, along with going through the symbols in the
order that we did above. This makes sure that we are going to get the right
answers, and is similar to what we should remember from basic algebra
classes in the past.
atabases usually consist of different tables with different column values and
types. However, some tables in the database consist of the same entities and
can be used to query two database columns with precision. To retrieve data
using this technique we use JOINS in SQL.
What are Joins?
Usually, we can query columns and rows using the SELECT statement.
However, SELECT statements only work for a single table and so is often
not useful for complex query operations. At this Joins come into operative
where they can query data from two or more tables with the help of
common columns present in the tables.
What are Unions?
Unions also are used to retrieve data from two or more tables. The only
difference between Joins and Unions is that Joins use only SELECT
statement whereas Unions use a different number of SELECT statement to
achieve the results.
How to Implement Joins?
Joins are usually implemented using two types of syntaxes. Explicit syntax
deals with the cartesian product of two tables. Whereas implicit syntax
deals with Where clauses. It is always recommended to use explicit
functionality because it is easy for queries to function and operate.
Cartesian product
Before going to learn about the advanced functionalities of Joins it is
important to know about the simple cartesian product.
Cartesian product is a simple mathematical operation that multiplies with
any entity without restrictions. By using the cartesian product you can
combine with any column of the other table.
To understand the cartesian product in layman terms it is just keeping two
tables side by side. For example, if Table A has 10 rows and Table B has 5
rows then the cartesian product will have a total of 50 rows.
Cartesian product is often under-discussed even though after being simple is
because it gives large output tables.
This cartesian product from SQL is explicitly known as cross join.
However, with the time SQL server has restricted cross join operations for
its huge data taking.
Here is the SQL statement for your reference:
SELECT * [ CROSS JOIN] {Enter parameters here}
SQL Self-connection
Self-connection refers to the connection between the same table and itself.
All databases process only one row in a table at a time. Users can access all
columns in one row, but only in one row. If information of two different
rows in a table is needed at the same time, the table needs to be connected
with itself.
To better understand self-joining, one table can be thought of as two
independent tables. In the FROM clause, the tables are listed twice. To
distinguish, each table must be given an alias to distinguish the two copies.
SQL UNION
In SQL Server, combined queries are completed through the UNION
operator. The UNION operator can be displayed by combining data FROM
multiple tables, but unlike joins, UNION is not implemented by adding
multiple tables in the from clause and specifying join conditions, but by
combining the results of multiple queries.
The following points should be noted when using the UNION operator:
(1) The number of columns in the two query statements is required to be
compatible with the data type of the columns.
(2) The column name in the final result set comes from the column name of
the first SELECT statement.
(3) In combination query, duplicate rows will be deleted from the final
result set by default unless the ALL keyword is used.
(4) The query results will automatically sort the columns in the SELECT
list from left to right, regardless of the position of the query relative to the
UNION operator.
Here is the syntax:
SELECT {UNION}
Merging multiple result sets through UNION is explained below by using a
server management studio.
The operation steps are as follows:
(1) Select Start → All Programs → SQL Server Management Studio in
turn. In the pop-up connection dialog box, select "SQL Server
Authentication", login name is "Your choice" and password is empty.
(2) In the "Microsoft SQL Server Management Studio" window, click the
"New Query" button, then enter the corresponding code in the code editing
area, and click the Run button on the toolbar. The results will be displayed
in the window.
SQL UNION {Enter parameters} Merge {Enter column names here}
Categories of Functions
Functions are classified according to the role they play on the SQL
database. The following are some of the function categories available:
1. Aggregate Functions-They do a calculation on a specific set of values
and deliver a single value. The aggregate values are used in the SELECT
LIST and HAVING clause. The aggregate functions are referred to as being
deterministic. This means that they return the same value when running on
the same input value.
2. Analytic Function-They calculate an aggregate value according to a
group of rows. They return many rows for different groups. The analytic
functions can be used to perform different computations like running totals,
percentages and others.
3. Ranking Functions-They provide a ranking value for each portioned row.
These kinds of functions are regarded as nondeterministic.
4. Rowset Functions- They're used to return an object that can be applied.
5. Scalar Functions-They work on a single value to return the same. There
are various kinds of scalar values. These include configuration function,
conversion function and others.
a) Configuration Functions-They offer information about the present
configuration.
b) Conversion Functions-They support data changing.
c) Cursor Functions-They provide information concerning cursors.
d) Date and Time Data Type-They are concerned with operations as
regards date and time.
6. Function Determinism-Functions that are found in SQL servers are either
deterministic or nondeterministic. Deterministic functions provide the same
answers when they are used. Nondeterministic functions, on the other hand,
offer different results when they are applied.
SQL Calculations
There are various mathematical functions build-in the SQL server. The
functions can be classified into 4 main groups, including Scientific and Trig
Functions, rounding functions, signs and random numbers. Although there
are numerous mathematical functions within each class, not all of them are
used regularly. The various classes are highlighted and explained below:
1. Scientific and Trig Functions-Under this category, there are various
subclasses found under it. These include P1, SQRT, and SQUARE. P1
function is used to compute the circumference and area in circles. How it
works: SELECT 2 *10. SQRT connotes square root. This function is used
most of the time. The function recognizes any number that can be changed
to float datatype. Example: SELECT SQET (36) Returns 6.SQUARE
means that you multiply any number by itself. The concept of Pythagoras
theorem is useful here. This means that Asquared+Bsquared=Csquared.
This can be performed as SELECT SQRT (SQUARE (A) + SQUARE(B))
as C.
2. Rounding Functions- Under this class, there are various subcategories
which include the CEILING and FLOOR. The ceiling function is helpful
when dealing with a float or decimal number. Your interest is to find out the
highest or lowest integer. Whereas the CEILING is the best highest integer,
the floor represents the lowest integer. The ROUND function is applied
when you want to round a number to the nearest specific decimal place.
This is expressed as ROUND (value, number of decimal places).
3. Signs- There are occasions that require that you obtain an absolute figure
of a number. For instance, the absolute value of -7 is 7. The absolute
number doesn't contain any sign. To assist you with this task, it's essential
to utilize the ABS function.
4. COS (X)-This function recognizes an angle expressed as radian as the
parameter. After an operation, you get a cosine value.
5. SIN (X)-This function notices a radian angle. After computation, it
gives back a sine value.
6. Sign-You can use a sign function when you want a negative, positive,
or zero value.
Definition
n SQL, subqueries are queries within queries. The subqueries usually use
the WHERE clause. Also called nested query or internal query, subqueries
can also restrict the data being retrieved.
Creating subqueries are more complex than creating simple queries. You
have to use essential key words such as, SELECT, DELETE, UPDATE,
INSERT and the operators such as, BETWEEN (used only WITHIN a
subquery and not WITH a subquery), IN, =, < =, > =, >, <, < >, and similar
symbols.
In composing a subquery, you have to remember these pointers.
Now, using the DELETE clause record with identity value 3 can be
dropped.
DELETE FROM LxryItms
WHERE
id = 3;
After you run the query above, you will receive a message stating 1 row(s)
affected.
Now, to verify the data with the view use the query below:
SELECT
*
FROM
LxryItms;
The result set is displayed in the picture below:
Finally, use the syntax below to retrieve desired records from the
underlying table to confirm that the “DELETE” statement in fact removed
the record:
SELECT
*
FROM
itms;
The result set is displayed in the picture below, which confirms that the
record with identity value 3 has been deleted from the items table:
Now, assume that you would like to insert the jobtitl column to the cntcts
view. You can accomplish this with the syntax below:
CREATE OR REPLACE VIEW cntcts AS
SELECT
fstName, lstName, extnsn, eml, jobtitl
FROM
emplyes;
The result set is displayed in the picture below:
Dropping a SQL View
The DROP VIEW statement can be utilized to delete an existing view from
the database, using the syntax below:
DROP VIEW [IF EXISTS] [db_name]. [vw_name]
The "IF EXISTS" clause is not mandatory in the statement above and is
used to determine if the view already exists in the database. It prevents you
from mistakenly removing a view that does not exists in the database.
You may, for instance, use the DROP VIEW statement as shown in the
syntax below to delete the organization view:
DROP VIEW IF EXISTS org;
SQL TRANSACTIONS
Any actions that are executed on a database are called as transactions.
These are actions that are executed logically, either manually by a user
or automatically using by the database program.
Or simply put, they are the spread of one or more database modifications.
For instance, every time you create a row, update a row, or delete a row
a transaction is being executed on that table. To maintain data integrity and
address database errors, it is essential to regulate these transactions.
Basically, to execute a transaction, you must group several SQL queries and
run them at the same time.
Conclusion
Application of SQL
The self-variable option lets you carry out the joining process on the same
table, saving you the time you spend organizing the final table. There are,
however, a few situations where this can be a good option. Imagine the
chart you created earlier has the columns consisting of country and
continent.
When faced with a task of listing countries located on the same continent, a
clearly outlined set below should give you a glimpse of the results expected.
SQL variable can further be subdivided into three different types: the left
join, the right join as well as the full outer join. The outer join primary role
is returning all the identified rows from a single table, and once the joining
target is archived, it includes the columns from another table. Outer joins
are different from inner joins in the essence that an inner join cannot
involve the unmatched rows in the final set of results.
When using an order entry, for instance, you may be faced with situations
where it is inevitable to list every employee regardless of the location, they
put customer orders. In such a case, this kind of joins is beneficial. When
you opt to use this kind of join, all employees, including those that have
been given marching orders, will be included in the final result.
This is a kind of outer join that is responsible for returning each row from
the first left side of the table and those row that match from the right side of
the table. In case there are no matches on the right side, left join returns a
null value for each of those columns. A type of outer join has the task of
returning each row from the right side of the table and merging with the
other side (left) of the table. Again, if there aren't any values for those digits
in the column, the join returns null values for them.
It has the task of returning rows from their initial location in the inner join,
and in case there is no match found, this join returns null results for those
tables.
This is a kind of variable that is essentially a product of Cartesian elements
that have been expressed in the SQL set up. Picture this; you require a
whole set of combinations available between both tables or even in just one
meal. You will have to use the cross join to achieve that technique. To help
you understand this join better, you can go back to the two tables we created
at the beginning of the article. Look at both the columns and try to compare
the impact each one of them has to the final result. The cross join plays an
essential in ensuring accuracy during merging. You ought to note that there
are apparent differences between cross joins and outer joins despite the fact
that the description makes them almost look similar.
Similarly, MySQL system has a slot that allows you to announce more than
one set of variables that has a common type of data. Again, most of the
technicians have had issues with how this command relays information to
related databases. In the various methods of storing variances and variables,
this one has proven to be more secure than others. Consequently, it has been
known to be the most popular of them all.
Variables can be applied in mathematical expressions, for example, adding
values altogether or combining and holding texts. This can be used as a
section of the general information. For your information, variables are also
applied in storing information so as one can participate in a kind of
calculations. Additionally, variables can be part of the parameters and are
used in procedural assessments. This is two in one method that not only lets
you declare a variable but also setting it up with values that have a similar
data type. Going back to the examples we gave earlier; we can affirm that
varchar is a kind of data that lets you sustain more than one kind of
character in just a single string.
Up to this point, you should be in a position to understand the kind of SQL
Exercises and Programs as well as the various types in existence. This will
not only let you be in an excellent place to tackle errors in case they occur
and prevent them from happening as well. When Mark Suaman, a renown
data scientist and a graduate of Havard University, first used varchar, he
recommended it for being efficient and accurate. He rated it among the best
types of data set in the market today. It does not have an allocation for
potential occurrences of errors. It is hard to interfere with such a highly
secure kind of data type.
Applications of SQL
Since its introduction in the computing world, SQL has played a significant
role in revolutionizing data storage in a systematic manner as well as direct
retrieval. As the digital world continues to grow steadily, the amount of data
stored quickly escalates, making organizations and personal data piling up.
Therefore, SQL acts as a platform where these data are stored while
offering direct access without the emergence of limitations. As such, SQL is
used in different sectors, including telecommunication, finance, trade,
manufacturing, institutional, and transport. Its presence primarily deals with
data but also accompanies other significant benefits on its application.
Data Integration
Across the sectors mentioned above, one of its main applications of SQL is
the creation of data integration scripts commonly done by administrators
and developers. SQL databases comprise of several tables which may
contain different data. When these data are integrated, it creates a new
experience essential for the provision of meaningful information, therefore,
increasing productivity. Data integration scripts are crucial in any given
organization, including the government, as it offers trusted data which can
be utilized to promote the achievement of the set goals.
Analytical Queries
Data analysts regularly utilize Structured Query Language to smoothen
their operations more so when establishing and executing queries. SQL
comprises multiple tables that consist of different datasets. When these data
are combined, it brings out more comprehensive information critical for any
individual or organization. The same is also applicable for data analysts as
they use a similar aspect. As they use an analytical query structure, queries,
and tables from SQL are fed into the structure to deliver crucial results from
varying sources. In this case, data analysts can readily acquire different
queries and customize them to have a more comprehensive data to depend
on as solutions.
Data Retrieval
This is another important application of SQL to retrieve data from different
subsets within a database with big data. This is essential in financial sectors
and analytics as to the use of numerical values typically consists of mixed
statistical data. The most commonly used SQL elements are create, select,
delete, and update, among others. The technique is made possible when the
user quickly can search the database and acquire the needed data as SQL
sieves the information to bring out the desired data. In some cases, the
language may deliver similar or related data when the required data is
missing. This is crucial as one can compare the results as well as make
changes where the need arises.
CODING HTML:
Eugene Gates
Introduction
TML stands for Hypertext Markup Language. It’s a special language that
web browsers understand. It’s basically a bunch of instructions about the
structure of the document.
Hypertext is probably the most important part of HTML letters because it
means that you can link one document to another one. Hypertext is a text
file that contains links to other text files.
This is the foundation stone of web, which at the beginning wasn’t much
more than few pages interconnected with links. Today, the web is no longer
just about text. Most of it is created by Hypermedia including video, photos
and music. But if you strip down all the bells and whistles, you will still
find this fundamental functionality of mutual linking between documents at
the core of any modern web application including Twitter, Gmail and even
the project we are about to build.
Markup means that HTML surrounds regular text with special code which
tells the browser how to display the content of the document. It tells the
browser what the structure of the document is.
Language means that HTML has some special syntax or the rules you need
to follow to create the correct content. Just like with other languages where
subjects and verbs have a special place in the sentence, HTML tags have a
special structure you need to use. For instance, when you need to nest tags,
you must place the closing part of the tag correctly.
When you build an HTML website, you actually need to learn different
coding languages (even though it is called an HTML website). The
structure or the core is provided by HTML, while CSS is about setting up
the looks and the visual feel, in order to make your website appealing and
pretty to look at. In order to make your website more dynamic and to add
additional interaction with the user, you can use JavaScript. As you can see,
in order to create a competitive website, you should at least learn the basics
and how these languages work.
These days, people use many devices with different screen sizes and
resolutions to browse the Internet, so it is very important to be able to
change the visible content based on what kind of device the user is currently
using. This is referred to as a responsive approach or responsiveness and we
will dive into it when we talk about CSS.
CSS provides styling for the structure. Let’s say you have a house with
three rooms. One room is a kitchen, one room is a bedroom and one is a
bathroom. Based on this description, you have a basic idea about the
structure of the house, but you have no idea how big those rooms are and
what are the colors of the walls. This is what CSS provides.
When it comes to real-world websites, the structure of the content is not
enough. You probably experienced this yourself. When you search on the
Internet for a restaurant, would you rather visit the one with a very nice,
professional looking website or the one with just a simple blank page with
general, unformatted text?
Regarding the content, they can both give you the same information as
menu, opening hours, contact, and so on, but as you know, it's the package
that sells the product.
That's why it's crucial to focus on the styling of your content in a way that's
pleasing and useful for the visitor of your website.
CSS (cascading style sheets) is technologies that will allow you to make
your page look anything you want without the need to change the structure
of the HTML document.
CSS is immensely powerful in transforming the styling of the website
without ever touching the content and its HTML structure.
Javascript provides the behavior. It gives HTML webpage event-driven
functionality, like what will happen when the browser finishes loading the
page or when the user clicks the Buy button on the web shop.
Javascript is the third language you are about to learn in this book. It is one
of the three languages every web developer must know and understand.
As you already know, HTML defines the content of web pages, CSS
specifies the layout and Javascript programs the behavior.
People usually don't appreciate the power of Javascript and this is probably
caused by two main reasons.
First, they lack the proper understanding of the language fundamentals.
Second, Javascript doesn't have a great reputation because in the early days
of the web, the vendors of browsers implemented Javascript however they
pleased. And this of course caused a lot of headaches to web developers,
because they couldn't be sure how their code would run in different
browsers, if at all.
Setting up frontend technologies is very easy. To get all three frontend
technologies up and running, you need just one product, a web browser.
Also, you will need a good plaintext editor. Just make sure it doesn't add
anything else to your code behind the scene. For this reason, you really
shouldn't use document processors like Microsoft Word or Apple Pages.
These are made for something entirely different and their built-in formatting
features will ruin your code.
Chapter 1. Fundamentals of HTML
What Is HTML?
Font Value
Arial, Times New Roman, Courier New, Georgia,
font-family
Verdana
font-size 9px, 10px……Large
font-style normal, italic, oblique
font-weight normal, bold, number
font-variant normal, small-caps
Text Style can be specified by { property: value }.
Example 6.1
<html>
<style type = "text/css">
#f{ font-family: Times New Roman; font-size: 28px; font-style: italic; font-
weight: bold; font-variant: normal }
</style>
<div id = "f">This is a text content using a different style.</div>
</html>
Output:
This is a text content using a different style.
Explanation:
“font-family, font-size, font-style, font-weight, font-variant.” specifies the
text style for the font.
Spacing
The line-height can specify line spacing.
The word-spacing can specify word spacing.
The letter-spacing can specify letter spacing.
Example 6.2
<html>
<style type = "text/css">
#lineSpacing{ line-height:500% }
#wordSpacing{ word-spacing: 10px }
#letterSpacing{ letter-spacing: 5px }
</style>
<p id = "lineSpacing">Line Spacing Sample.</p>
<p id = "wordSpacing">Word Spacing Sample.</p>
<p id = "letterSpacing">Letter Spacing Sample.</p>
</html>
Output:
Explanation:
“line-height:500%” specifies the line height as 500%.
“word-spacing: 10px” specifies the word spacing as 10px.
“letter-spacing: 5px” specifies the letter spacing as 5px.
Divided Style
The dividing <div></div> tags are used to group their content elements as
blocks. <div> tags are useful for styling purposes.
<div class = “xxx”></div>
<div id = “xxx”></div>
The <div> tag can have id and class attribute in css style.
Example 6.3
<html>
<style type = "text/css">
.d1{font-style: italic; color: purple;}
#d2{font-family: arial black; color: blue;}
</style>
<body>
<div class = "d1"> <p>AAAAA</p> <p>BBBBB</p> <p>CCCCC</p>
</div>
<div id = "d2"> <p>EEEEE</p> <p>FFFFF</p> <p>GGGGG</p>
</div>
</body>
</html>
Output:
AAAAA
BBBBB
CCCCC
EEEEE
FFFFF
GGGGG
Explanation:
<div class = "d1"></div> is divided as the first group which contains three
pairs of <p> tags. They use “.d1” style.
<div id = "d2"></div> is divided as the second group which contains other
three pairs of <p> tags. They use “#d2” style.
Span Style
<span></span> can be used to group elements for styling purposes (using
the class or id attributes).
<span class = “xxx”></span>
<span id = “xxx”></span>
The <span> tag can have id and class attribute in css style.
Example 6.4
<html>
<style type = "text/css">
div{background-color: yellow}
.d1{font-style: italic;color: purple;}
#d2{font-family: arial black;color: blue;}
</style>
<body>
<div><p>This is AAA text,
<span class = "d1">This is BBB text,</span>
This is CCC text,
<span id = "d2">This is DDD text,</span>
This is EEE text.</p></div>
</body>
</html>
Output:
This is AAA text, This is BBB text, This is CCC text, This is DDD
text, This is EEE text.
Explanation:
The above uses <span></span> tags to set the css style of two pieces of text
within a paragraph which is contained in a block.
<span> is very much like a <div> element, but <div> is a block-level
element whereas a <span> is an inline element.
Border Style
border-style: value
“border-style: value” can set the border style by specifying different value.
The “value” may be “solid, double, dashed, dotted, groove, ridge, inset,
outset”.
Example 6.5
<html>
<style type = "text/css">
#b1{border-style: solid; border-width: 10px;}
#b2{border-style: double; border-width: 10px;}
#b3{border-style: dashed; border-width: 10px;}
#b4{border-style: dotted; border-width: 10px;}
#b5{border-style: groove; border-width: 10px;}
#b6{border-style: ridge; border-width: 10px;}
#b7{border-style: inset; border-width: 10px;}
#b8{border-style: outset; border-width: 10px;}
</style>
<body>
<p id = "b1">This is solid border.</p><br>
<p id = "b2">This is double border.</p><br>
<p id = "b3">This is dashed border.</p><br>
<p id = "b4">This is dotted border.</p><br>
<p id = "b5">This is groove border.</p><br>
<p id = "b6">This is ridge border.</p><br>
<p id = "b7">This is inset border.</p><br>
<p id = "b8">This is outset border.</p><br>
</body>
</html>
Output:
Explanation:
The “border-style: value” may be “solid, double, dashed, dotted, groove,
ridge, inset, outset”.
The “border-width: 10px” specifies the border width as 10 px.
Border Color
border-color: value
“border-color: value” can set the bonder properties for color.
Example 6.6
<html>
<style type = "text/css">
#b5{border-style: groove;border-width: 20px; border-color:blue }
#b6{border-style: ridge;border-width: 20px; border-color:purple }
</style>
<p id = "b5">This is groove border.</p>
<p id = "b6">This is ridge border.</p>
</html>
Output:
Explanation:
“position:relative; top: 3%; left: 5%” specifies the relative position based on
the resolution or size of the browser window.
Html Symbols
In HTML documents, when you meet some special symbols such as &, <,
>, and space, you need to use corresponding codes, & < >
Symbol
Source Codes
s
< <
> >
& &
“” " "
© ©
® ®
space
! !
: ;
Example 6.11
<html>
<body>
< Java in 8 Hours > & < Python in 8 Hours > are very
books!<br>
Copyright © 2016 by Ray Yao
All Rights Reserved!
</body>
</html>
Output:
< Java in 8 Hours > & < Python in 8 Hours > are very books!
Copyright © 2016 by Ray Yao All Rights Reserved!
Explanation:
Symbol Code
s
< > < >
> >
& &
© ©
space
! !
Chapter 3. Forms In HTML
Web Forms Basics
eb pages are not just about reading documents and articles, but are also for
social and business applications. You can hardly imagine any kind of web
app without asking some data from users—just think about the most
common functions, such as login and registration.
HTML forms are the part of the markup since the earliest versions, and
now, after several twists—that are related to HTML-XHTML debates—we
have a refined model of forms in HTML5, which still works with older
browsers.
How Web Forms Work
This shows a web form in
action, which contains user interface components—or, with another name,
controls. Not only textboxes, checkboxes and radio buttons are controls in
this form, but labels, and frames surrounding the sections, too, as well as
the Register button.
A web form in action
To design and code web forms, you need to understand how they work.
Here is a simplified overview:
When the browser displays a web form, it simply renders its controls just
like any other element, such as text, menus, images, and so on. Users fill it
out, and then click a button that submits the form. The submission of a form
means that the browser collects the data entered by the user, puts it into an
HTTP/HTTPS request, and sends it to the server. When the server side
receives the request, the web server finds out the type of application or
module to dispatch the request with the collected data. The entity receiving
the request analyzes the information collected, and decides what to do next.
For example, if the request contains registration data, the web server may
store it in the database and send back a message about the success of
registration. Or, if the data is invalid, for example a mandatory field has not
been filled out, the webserver might send back the original form with the
data specified by the user, and with additional markup that summarizes the
issues found by the server application.
So, this process contains these fundamental steps:
1. The browser collects the form data, and sends it to the web server.
2. The web server processes the data, and sends back the result to the
browser.
3. The browser visualizes the result (which may be a web page, an error
message, or some other kind of information, etc.)
Of course, the most difficult part of this process is step 2, which is carried
out at the server side. There are many server technologies that can process
web forms, but in this book we do not dive into them, we will only scratch
the surface.
As the web evolved, and users expected fluent experience, new
asynchronous technologies appeared, such as AJAX (Asynchronous
JavaScript and XML). These do not expect the web server to retrieve a full
web page, but only a part of the page—affected by the changes in regard to
the information the users specified. This approach results in smaller
network packages, and less flickering on the screen. The main virtue of the
asynchronous technologies is that they can send data to—and retrieve data
from—a server asynchronously in the background, without preventing user
interaction.
In this chapter you will focus on building and using web forms at the client
side.
Representing Web Forms in HTML
The key HTML element is <form> that defines a web form within a page.
The simplest web form takes only a few lines of markup:
<form action="ProcessAtServer.html">
<input type="submit" value="Do it!"/>
</form>
rames used to decrease day by day. At the present time the frame is not
useless, because it is quite hard to print finished pages using frames
together. Apart from it, many dislike it. Instead, CSS is now used to divide
a page into more than one section. But there is a need to have some idea
about frames to enrich the knowledge base of HTML.
Example Programs
<html>
<head>
<title> www.lifeguruji.tk </title>
</head>
<body bgcolor ="#00cc99">
<frameset rows ="12%,88%">
<frame src = "style.html" scrolling ="no">
<frameset cols ="27%,74%">
<frame src ="link.html">
<frame src ="textfor.html">
</frameset>
</frameset>
</body>
</html>
Create a folder with any file name and put it in style.html, link.html and
textfor.html three html files. Open a Notepad and enter the code above and
click on Save as the File menu, save as file name: index.html, Save as type:
All files, open the index.html file using Mozilla Firefox or Google Chrome,
and check how it’s look...
Discuss the program
First, frameset rows = "12%, 88%"> is divided into two parts along the row
on the entire page.
Through the frameset cols = "27%, 74%"> the bottom row is divided into
two sections along the column.
<frame src = "style.html" scrolling = "no"> The style.html page is displayed
in the first frame.
<frame src = "link.html"> and <frame src = "textfor.html"> Arrangements
are made to display links.html and textfor.html pages in the 1st and 2nd
frame respectively.
Eye Frames
Eye frames are one of the main ways to display one or more web pages on a
web page. It is important to publish a link to different web pages on topics
relevant to the presentation, as well as it is not bad if it can be scrolled in
the short space.
Example Programs
<html>
<head>
<title> www.lifeguruji.tk</title>
</head>
<body bgcolor=" #f00">
<center>
<h2 style="color:#f00">This is an example of iframe.</h2><br/>
<iframe src="http://www.lifeguruji.tk/bangla/html/" width="350"
height="170">
<p>This browser does not support iframes.</p>
</iframe>
</center>
</body>
</html>
Open a Notepad and enter the code above and click on Save as from the
File menu, save as file name: index.html, Save as type: All files, open the
index.html file using Mozilla Firefox or Google Chrome, and check how
it’s look.
Layout
On the page layout, depending on how good a webpage should be.
Previously all web site layouts were made using HTML only. Currently
CSS is used with HTML. Rows and columns of <table> are used to create
layouts using HTML only.
Example Programs
<html>
<head>
<title> www.lifeguruji.tk</title>
</head>
<body bgcolor="green">
<table width="400" border="0">
<tr>
<td colspan="3" style="background-color: #93C;">
<h1> Web Page header</h1>
</td>
</tr>
<tr valign="top">
<td style="background-color: #C99;width:100px;text-align:top;">
<p><b>Side bar</b><br />
<a href="#">PHP</a>
<br />
<a href="#">HTML</a>
<br />
<a href="#">CSS</a>
<a href="#">Wordpress</a>
</p></td>
<td style="background-color:#EEEEEE;height:200px;width:400px;text-
align:top;"><h2 style="color:#900">This is heading.</h2>
<p style="color: #006">This is a paragraph.This is a paragraph. This is a
paragraph.<br />
This is a paragraph.This is a paragraph. This is a paragraph.<br />
This is a paragraph.This is a paragraph.This is a paragraph.<br />
This is a paragraph.This is a paragraph.This is a paragraph.</p></td>
</tr>
<tr>
<td colspan="2" style="background-color:#999;text-align:center;">
Copyright © 2018 by Omar Faruq</td>
</tr>
</table>
</body>
</html>
Open a Notepad and enter the code above and click on Save as from the
File menu, save as file name: index.html, Save as type: All files, open the
index.html file using Mozilla Firefox or Google Chrome, and check how
it’s look...
Chapter 5. How to Put Images in HTML?
Example
You can see that I have marked two images – one is of Albert Einstein and
other is of Wikipedia Logo. Don’t you agree that these images have made
this page lively? Images on the web page can be used in two ways:
ü✓ One way is just show image. Just show; nothing else.
ü✓ Other way is to use image as hyperlink. It means when you click on the
image, it will take you to some other page. How interesting!
Learning The Details
How do we show image on web page? We use <img> tag for this purpose.
Please check the example below:
<img src="location of the image" alt="alternate text" width="width in
pixel" height="height in pixel"></img>
We start <img> tag and then we close with </img> tag like we do for any
HTML tag. But then we use various other attributes to make sure image is
shown on the web page. Let’s look into these attributes in the table below.
Table 6.1: Attributes of the <img> tag
<img> tag attribute Purpose
src src stands for source. Like hyperlink, you enter address of the
image for this attribute. Address is the location where this image has
been stored.
The address could be internet based image. It means image is stored
at internet somewhere like any web page. Example is Albert Einstein
image stored at Wikipedia. Address is:
https://upload.wikimedia.org/wikipedia/commons/thumb/3/3e/Einstein_19
21_by_F_Schmutzer_-‐ _restoration.jpg/220px-‐
Einstein_1921_by_F_Schmutzer_-‐ _restoration.jpg
Or it could an address from your computer/laptop hard disk. It means
the image is stored somewhere in your local computer hard disk. You
provide folder location of the image. Example is -‐ “file://C:/
Books\HTMLforKids/mybook.jpg”
You can use most types of images such as jpg, jpeg, png, gif and bmp.
alt alt stands for alternate text. This is the text shown on web page
if image could not be shown on web page due to some reason. It is
like a backup plan. You want to show some text in case image could not
be shown due to some problem.
width This tells the width of the image. If you don’t provide this value,
then it will show image in its original width.
Width is measured in pixel. One pixel is like a dot on the screen. Just like
you measure distance in meter or centimeter; in the same way you
measure length of the image in pixel.
height Tells the height of the image. Similar to width, it is also measured
in pixel.
If you don’t provide this value, then it will show image in its original
height.
Let me show you image in HTML. I am going to use Albert Einstein image
address given in the table above and will show that in my HTML page. I
will make height 200 pixel and width also 200 pixels; like square. The
HTML looks like following:
<html>
<head>
<title></title>
</head>
<body>
<h2>Albert Einstein</h2>
<img
src="https://upload.wikimedia.org/wikipedia/commons/thumb/3/3e/Einstein
_1921_ by_F_Schmu tzer_-_restoration.jpg/220px-
Einstein_1921_by_F_Schmutzer__restoration.jpg” alt="Albert Einstein"
width="200" height="200"></img>
</body> </html>
The HTML page will be displayed as shown below.
ables are very useful to represent the data in grid format. The data is divided
into rows and columns. It helps us to understand the data on two axes. Each
block in the table is called as table cell. Let’s take a look at how table is
created in the HTML.
Table Creation
<table> element is used to create a table. The contents of the table are
written out row by row. <tr> element is used to represent a start of each
row. <tr> means table row. Each cell of the table is represented using a <td>
element. A table row can also be divided into table headings with
the <the> tag. Let’s take a closer look at table creation with an example
<!DOCTYPE html>
<html>
<body>
<table>
<tr>
<td>A</td>
<td>X</td>
<td>1</td>
</tr>
<tr>
<td>B</td>
<td>Y</td>
<td>2</td>
</tr>
<tr>
<td>C</td>
<td>Z</td>
<td>3</td>
</tr>
</table>
</body>
</html>
Table looks good with borders. We will learn how to draw borders around
the tables using CSS.
Table Headings
The heading for either a row or column is represented using <th> element.
<th> means table heading. Foe an empty cell you should use <td> or <th>
element otherwise the table will not be created correctly. The scope attribute
can be used on the <th> element to indicate whether it is row or column. It
takes the values, row to indicate heading for a row or col to indicate
heading for a column. The contents of <th> element is displayed in the
bold and centered way. Table can also be given caption using <caption> tag.
<!DOCTYPE html>
<html>
<body>
<table>
<caption><b>Ticket Sales</b></caption>
<tr>
<th></th>
<th scope="col">Saturday</th>
<th scope="col">Sunday</th>
</tr>
<tr>
<th scope="row">Tickets Sold</th>
<td>50</td>
<td>20</td>
</tr>
<tr>
<th scope="row">Total Sale</th>
<td>100</td>
<td>150</td>
</tr>
</body>
</html>
Spanning Columns
Sometimes you may need the entries in the table to stretch across many
columns. For this purpose, colspan attribute is used. It indicates how many
columns cell should run across.
<!DOCTYPE html>
<html>
<head>
<style>
table, th, td {
border: 1px solid black;
border-collapse: collapse;
}
th, td {
padding: 5px;
text-align: left;
}
</style>
</head>
<body>
<h2>Cell that spans two columns:</h2>
<table style="width:100%">
<tr>
<th>Name</th>
<th colspan="2">Telephone</th>
</tr>
<tr>
<td>Mr ABC</td>
<td>666 77 854</td>
<td>888 77 855</td>
</tr>
</table>
Spanning Rows
In order to span a cell more than one row, you can use
the rowspan attribute. Check example below.
<html>
<head>
<style>
table, th, td {
border: 1px solid black;
border-collapse: collapse;
}
th, td {
padding: 5px;
text-align: left;
}
</style>
</head>
<body>
<h2>Cell that spans two rows:</h2>
<table style="width:100%">
<tr>
<th>Name:</th>
<td>Mr XYZ</td>
</tr>
<tr>
<th rowspan="2">Telephone:</th>
<td>222 77 854</td>
</tr>
<tr>
<td>888 77 855</td>
</tr>
</table>
</body>
</html>
There is lot of code in HTML for formatting the table. But now we can use
CSS for better formatting. Hence, details about table formatting in HTML
have been omitted.
Chapter 7. Fundamentals Of CSS
eb page development used to be relatively simple. Developers simply write a Web page in
HTML that can be accessed by other similar computers. But times are changing in two
ways. First, Web sites are becoming vastly more complex, often with hundreds if not
thousands of Web pages, dynamic HTML that adjusts to different users, and greater demands
from the customer base. Writing a page at a time can be a nightmare for developers, a
problem for maintenance, and can cause inconsistencies across pages within a Web site that
annoy the customers or viewer.
Second, Web pages used to be accessed by a computer with a monitor, or even a laptop with
a reasonable viewing area. Now we access Web pages with tablets, small web books, phones,
and even black and white eBook readers (like that Amazon Kindle, pre-Fire). Viewers using
non-computer devices can get very frustrated as the viewing area exceeds the screen by
several thousand percent, or keystrokes are required, or data entry exists with no easy way to
enter the data. There is a wide diversity of browsers on the market now, but often, Web
developers insist on developing for the 1024 x 768 pixel (or larger) computer monitor.
Web developer or managers should try to make their Web pages as universally accessible and
available to their viewers or client base as possible, including those who want to view
content on a smaller device. This can be done with newer technology, newer formatting, and
newer Web page validation that have not been available for that long.
Previous versions of HTML (versions 3.2 and before) make use of the<font> tag and
background tags for every HTML element, so that a table at the top of the page could (and
often did) have different formatting than a table at the bottom of the page. The result was that
many Web pages had vastly different appearances in HTML 3.2. Studies showed that this
annoyed the users. A user who was used to one page would click on a link and be exposed
to a whole new page, with new formatting, new form and table colors, and an overall new
look. HTML 4.0 attempted to change this, by standardizing the look of every page, often
through the use of a Cascading Style Sheet (also known as a CSS). The conceptual
difference between HTML 3.2 (and before) and HTML 4.0 (and beyond).
Conceptual Changes in Html 4.0
This shows how we can manage the formatting of a page from a single CSS. By using a
single CSS linked to every page on your site, you not only streamline the look of your Web
page across your site, but you also streamline maintenance and development costs by
defining the formatting of page elements (like tables, text, and lists) only once.
Html Styles
The ways of formatting Web pages that were accepted in the 1990s and early 2000s have
fallen out of favor.
Implementing styles requires some changes to your HTML. To make formatting consistent,
you now use a style attribute to determine how something should look. This caused a change
in the HTML language. Older tags, like the <font> tag, and older attributes, like bgcolor or
border that used to control the appearance of HTML elements are now considered
deprecated, or obsolete. The format for the style attribute is as follows:
<tagname style=" attribute1: value1;
attribute2: value2;
attribute3: value3;">
You can usually apply a style attribute to almost any HTML tag (like<li>,<td>,<p>, etc.).
However, if you are just typing, and you want to change the font, color, etc., of the next
paragraph or the rest of the sentence, you can use either a <div> or a <span> tag. A <div>
tag returns to the next line before going any further. A <span> tag keeps you on the same
line, and allows you to make a single line have different fonts, colors, etc. For example, the
following <div> tag shows how to display text in red:
<div style="color: Red;">
This text will be red
</div>
Fonts
Fonts are great for giving your page a crisp look that differs from the default font. The style
attribute (or the <font> tag on older, pre-4.0 Web pages) is used to control the font displayed
on your HTML page. Table 1 shows some things you can do with the style attribute and most
tags, or use the <span> tag or the <div> tag (or the <font> tag, if you must).
Current/Strict Deprecated/Transitional
Example
(New Way -- HTML 4.0) (Old Way -- HTML 3.2)
<div style="font-family: <font face="Comic Sans MS,
Comic Sans MS, Arial, arial,helvetica"> Browser will try
Change the Helvetica;">
Browser will try Comic Sans Comic Sans MS
Font (Font Browser will try Comic Sans
MS first, then Arial, then first, then Arial,
Family) MS first, then Arial, then
Helvetica then Helvetica
Helvetica
</font>
</div>
<span style="font-size:
<font size="5">
Set Font Size 18pt;">
define the font size define the font size
(Absolute) define the font size
</font>
</span>
<font size="+3">
Increase Font <td style="font-size: 2em;"> increase the size of the increase the size of
Size increase the size of the text
text the text
(Relative) </td>
</font>
<span style="font-size:
<font size="-2">
Decrease .6em;">
decrease the size of the decrease the size
Font Size decrease the size of the
text of the text
(Relative) text
</font>
</span>
Table 1. Setting Fonts
pt vs. px vs. em
When you are specifying font size, you can specify the size in one of three ways:
pt gives you the absolute point size which is defined by the user's client
machine.
px gives you the absolute pixel height, which is independent of machine
(but can shrink with lower resolution and grow with higher resolution). This
often used for setting borders and margins.
em gives you the relative height, which is gives the height as the number of
times the current height. This is a relative measure, depending on the current
size.
You choose what you need.
Colors
Colors on computer monitors are defined by light, not pigment, so the primary colors are red,
green, and blue. Also unlike pigments, combining all the colors of light results in a white
light, whereas removing all the colors of light results in a black color. Figure below shows
how the primary colors mix, and how that mixture looks, at a very
high level.
Colors are specified one of two ways. First, you can use an actual color (red, blue, purple,
etc.) Second, you can use a RGB (red, green blue) representation of the color by providing
the red component, the green component, and the blue component, each a number from 0
(hexadecimal #00 – black) to 255 (hexadecimal #ff – bright). For example, to get this color
of purple, you specify <span style="color: #880088">. You can also use decimal with an
RGB function, like <span style="color: rgb(133, 0, 133)">.
As with fonts, colors can be controlled using the <font> tag, but newer standards suggest
using a style attribute, possibly in conjunction with a <span> or <div> tag. Table 6 shows
the HTML for some color manipulation.
Current/Strict Deprecated/Transitional
Example
(New Way -- HTML 4.0) (Old Way -- HTML 3.2)
<span style="color: red"> <font color="red">
Set the Change text
Change text color to red Change text color to red
Color color to red
</span> </font>
<td style="background: rgb(221, 153, Change
<td bgcolor="#dd99dd">
221)"> background to
Set the Change background to whatever
Change background to whatever whatever color
Background color this is using Hex
color this is using RGB this is using
</td>
</td> RGB
Table 2. Using Colors
Alignment and Borders
You can use styles to control borders or to align images or text. The use of the float attribute
can also make text float to the left or right with other text wrapping around the floating
object. Table 7 shows some use of alignment.
Current/Strict Deprecated/Transitional
Example
(New Way -- HTML 4.0) (Old Way -- HTML 3.2)
Place Border on Table <table <table border="1"> cell 1 cell 2
style="border-width: 1px; <tr> cell 3 cell 4
border-style: outset;"> <td>cell 1</td>
<tr> <td>cell 2</td>
<td </tr>
style="border-width: 1px; <tr>
border-style: inset;"> <td>cell 3</td>
cell 1 <td>cell 4</td>
</td> </tr>
<td </table>
style="border-width: 1px;
border-style: inset;">
cell 2
</td>
</tr>
<tr>
<td
style="border-width: 1px;
border-style: inset;">
cell 3
</td>
<td
style="border-width: 1px;
border-style: inset;">
cell 4
</td>
</tr>
</table>
Table 3b. Alignment and Borders (continued)
Chapter 8. CSS
ou can use a lot of other CSS properties to work with links and tables. You
will learn how you can add color to each column of the chart to make it
stands out of the rest. Similarly, you will also learn how to beautify the
forms such as submissions forms, survey forms and any other form that you
have created in HTML.
You will be able to create beautiful buttons that can be integrated into the
forms. Each code example also contains the displayed results of the code.
You can take up the code, recreate it, modify or run it to see how it works.
Even simply reading it will give you a general idea of how you have to
proceed.
<html>
<head>
<style>
a{
color: green;
}
</style>
</head>
<body>
<h1> Let me tell you a story.</h1>
<h2><b><a href="default.asp" target="_blank">Watch the video story here.
</a></b></h2>
<p> Once, there was an eagle that flew high in the skies,
<br> touching upon the tip of the mountains.
<br> One day she found a ring, stuck in the branch of an apple tree. </p>
<p>She took it and flew to her nest. While playing with it, she got her head
stuck in it.
<br>She didn't panic or hit her head on the stump of a tree to get rid of it.
<br>One day she drenched her head in oil and the ring came off of her
neck.</p>
</body>
</html>
The result of the above style is as under. You can see the second line of
code which has got a link hidden inside.
Let me tell you a story.
Watch the video story here.
Once, there was an eagle that flew high in the skies,
touching upon the tip of the mountains.
One day she found a ring stuck in the branch of an apple tree.
She took it and flew to her nest. While playing with it, she got her head
stuck in it.
She didn't panic or hit her head on the stump of a tree to get rid of it.
Then, one day she drenched her head in oil and the ring came off of her
neck.
------------------------
CSS links are critical because many a time you have to connect your
webpage to another website to offer your users an amazing and fruitful
experience. There are four kinds of links that you can use for different
purposes. They are named as a: link, a: hover, a: active, a: visited. Each link
has a specific purpose. For example, a: hover is used to allow users to hover
over the mouse on the link and make it open. Let’s try to create links by all
the four methods.
<html>
<head>
<style>
/* This is an unvisited link */
a:link {
color: green;
}
/* This is a visited link. */
a:visited {
color: blue;
}
/* This is a hover link. */
a:hover {
color: violet;
}
/* This is a selected link. */
a:active {
color: red;
}
</style>
</head>
<body>
<h1> Let me tell you a story.</h1>
<h2><b><a href="default.asp" target="_blank">Watch the video story here.
</a></b></h2>
<p> Once, there was an eagle that flew high in the skies,
<br> touching upon the tip of the mountains.
<br> One day she found a ring, stuck in the branch of an apple tree.</p>
<p>She took it and flew to her nest. While playing with it, she got her head
stuck in it.
<br>She didn't panic or hit her head on the stump of a tree to get rid of it.
<br>One day she drenched her head in oil and the ring came off of her
neck.</p>
</body>
</html>
You might be thinking that I had entered four links, but just one color can
be seen in the results if you have already tested the code. Links change their
status. In the start, they are unvisited. Then you hover your mouse over
them. Then you click them open and leave them visited. So, technically,
you can add four different colors according to the status of your link. Let’s
see what other things we can do to the links. Also, we can decorate the text
of links and also add color to the background. Let’s see how to do that.
<html>
<head>
<style>
/* This is an unvisited link */
a:link {
color: green;
text-decoration: none;
background-color: yellow
}
/* This is a visited link. */
a:visited {
color: blue;
text-decoration: none;
background-color: gray
}
/* This is a hover link. */
a:hover {
color: violet;
text-decoration: underline;
background-color: pink
}
/* This is a selected link. */
a:active {
color: red;
text-decoration: underline;
background-color: hotpink
}
</style>
</head>
<body>
<h1> Let me tell you a story.</h1>
<h2><b><a href="default.asp" target="_blank">Watch the video story here.
</a></b></h2>
<p> Once, there was an eagle that flew high in the skies,
<br> touching upon the tip of the mountains.
<br> One day she found a ring, stuck in the branch of an apple tree.</p>
<p> She took it and flew to her nest. While playing with it, she got her
head stuck into it.
<br> She didn't panic and hit her head into the stump of the tree to get rid of
it.
<br> One day she drenched her head in oil and the ring moved out of her
neck. </p>
</body>
</html>
CSS Tables
CSS allows you to transform the way your tables look in HTML. You can
add colors to the headings and to the columns. The font style and font size
of the text inside the tables can also be changed. Let’s create one.
<!DOCTYPE html>
<html>
<head>
<style>
#countries {
font-family: "Courier New", Gerogia, Helvetica, sans-serif;
border-collapse: collapse;
width: 80%;
}
#countries td, #countries th {
border: 2px solid green;
padding: 6px;
}
#countries tr:nth-child(even){background-color: violet;}
#countries tr:hover {background-color: #ddd;}
#countries th {
padding-top: 15px;
padding-bottom: 15px;
text-align: left;
background-color: #ffAc2b;
color: gray;
}
</style>
</head>
<body>
<table id="countries">
<tr>
<th>Country</th>
<th>Capital</th>
<th>Reasons for fame</th>
</tr>
<tr>
<td>Germany</td>
<td>Berlin</td>
<td>BMW</td>
</tr>
<tr>
<td>United States of America</td>
<td>Washington DC</td>
<td>Marvel</td>
</tr>
<tr>
<td>China</td>
<td>Beijing</td>
<td>cheap products</td>
</tr>
<tr>
<td>Pakistan</td>
<td>Islamabad</td>
<td>Footballs</td>
</tr>
<tr>
<td>Japan</td>
<td>Tokyo</td>
<td>Robotics</td>
</tr>
<tr>
<td>United Kingdom</td>
<td>London</td>
<td>Thames</td>
</tr>
<tr>
<td>Egypt</td>
<td>Cairo</td>
<td>Pyramids</td>
</tr>
<tr>
<td>India</td>
<td>New Delhi</td>
<td>Taj Mehal</td>
</tr>
<tr>
<td>Brazil</td>
<td>Sao Paulo</td>
<td>Statue of Jesus</td>
</tr>
<tr>
<td>Kingdom of Saudi Arabia</td>
<td>Riyadh</td>
<td>Pilgrimage</td>
</tr>
</table>
</body>
</html>
The results of the above code example can be seen below. You can change
the values and yield out a different output in the internet browser. Tables are
an essential element for a web page. You need them if you are running a
website that displays information about the rise and fall in the prices of
stock market shares. If you don’t style them properly with CSS, your
visitors are not going to like their dull and boring look. Appropriately
colored tables appear well on the website and keep visitors engaged for a
while.
You can alter the colors, the border, and padding by making slight changes
in the HTML document. Adding more columns or rows to suit your specific
requirement is also being done. In the above example, I have added
background colors, padding, border colors and have also adjusted the width
of the columns. You can take the example document and customize for
learning practice.
CSS Forms
HTML provides us with an easy way to create different types of forms that
we can use to collect user information like their usernames, passwords, and
email addresses. Some are subscription forms while others are survey
forms. When we create an HTML form, its look is rigid and dull. Thanks to
CSS, we can change that. We can make it look exceptionally well. Let’s
create a form and then transform its look by adding some simple CSS
properties.
<!DOCTYPE html>
<html>
<style>
input[type=text], select {
width: 100%;
padding: 15px 25px;
margin: 10px 0;
display: inline-block;
border: 2px solid green;
border-radius: 6px;
box-sizing: border-box;
}
input[type=submit] {
width: 50%;
background-color: pink;
color: black;
padding: 12px 18px;
margin: 10px 0;
border: 2px solid green;
border-radius: 2px;
cursor: pointer;
font-size: 25px
}
input[type=submit]:hover {
background-color: #45b049;
}
div {
border-radius: 4px;
background-color: #f1f1f1;
padding: 15px;
}
</style>
<body>
<h1>I will be using CSS to style this raw HTML Form</h1>
<div>
<form action="/action_page.php">
<label for="name">Please enter your first Name</label>
<input type="text" id="name" name="firstname" placeholder="Plese
enter here..">
<label for="lname">Please enter your last Name</label>
<input type="text" id="lname" name="lastname" placeholder="Please
enter here..">
<label for="country">Where do you live?</label>
<select id="country" name="country">
<option value="USA">USA</option>
<option value="canada">Canada</option>
<option value="UK">UK</option>
<option value="china">China</option>
<option value="pakistan">Pakistan</option>
<option value="france">France</option>
</select>
<input type="submit" value="Submit">
</form>
</div>
</body>
</html>
The result is as under:
I have styled the border, the input fields, the submit button and a lot more.
Let’s learn more about designing the buttons, as they are an essential part of
forms on your web page.
<!DOCTYPE html>
<html>
<head>
<style>
input[type=refresh], input[type=submit], input[type=process] {
background-color: #4CAFBB;
border: 2px solid green;
color: white;
padding: 19px 34px;
text-decoration: none;
margin: 6px 4px;
cursor: pointer;
}
</style>
</head>
<body>
<h1>You are seeing styled input buttons.</h1>
<input type="refresh" value="Refresh It">
<input type="process" value="Process">
<input type="submit" value="Submit">
</body>
</html>
The result is as under:
ou can add images to your documents using the img tag, or you can add a
background image to the entire document.
Keywords
top left center left bottom left
top center center center bottom center
top right center right bottom right
These keywords can be written in either order. For example, “top left” and
“left top” will both work correctly. The other value will default to center if
you only specify a single value.
You can also use percentages to set the position.
background-position: 30% 80%;
If you want to position the image in the top left 0% 0% is the value, and
100% 100% would place it in the bottom right. Setting the background-
position to 50% 50% would center the image, as would center center.
The following list shows how keyword settings match percentage settings:
Keywords Percentages
left top 0% 0%
center top 50% 0%
right top 100% 0%
left center 0% 50%
center center 50% 50%
right center 100% 50%
left bottom 0% 100%
center 50% 100%
bottom
right bottom 100% 100%
If you use keywords or percentages, your background image’s position will
adjust to the size of the window. You can also use pixels to set a non-
adjusting position:
background-position: 20px 20px;
Adjusting background color or image position.
You can use the background-clip property to specify whether the
background includes the border, padding, or only the content.
div {
padding:10px;
border: 5px dotted #000;
background-color: #f00;
background-clip:border-box;
}
div {
padding:10px;
border: 5px dotted #000;
background-color: #f00;
background-clip:padding-
box;
}
div {
padding:10px;
border: 5px dotted #000;
background-color: #f00;
background-clip:content-box;
}
Adding more than one image to the background
With CSS3, you can specify multiple background images. If you are
supporting old browser versions, you can specify one background image
with the html tag and another with the body tag.
CSS approach
body {
background-image: url('logo.gif'), url('draft.gif');
background-position: bottom right, 50% 50%;
background-repeat: no-repeat;
}
Older browser version approach
html {
background-image: url('logo.gif');
background-position: bottom right;
background-repeat: no-repeat;
}
body {
background-attachment: fixed;
background-image: url('draft.gif');
background-position: 50% 50%;
background-repeat: no-repeat;
}
Fixing a background image to avoid scrolling
You can use the background-attachment property to fix an image in place
and prevent it from scrolling with rest of the page’s content.
body {
background-attachment: fixed;
background-image: url('draft.gif');
background-position: 50% 50%;
background-repeat: no-repeat;
}
Value Description
repeat The background repeats horizontally and vertically.
This is the default setting.
repeat-x The background repeats horizontally but not vertically.
repeat-y The background repeats vertically bit not horizontally.
no- The background does not repeat horizontally or
repeat vertically.
How do I resize a background image to fit an element?
You can use the background-size property to resize a background image to
fit a larger or smaller element automatically.
Value Description
contain Scales the image so the height and width fit in the element
cover Scales the image so the height or width fits (whichever is
smaller)
length Sets the height and width
If you only specify one value, the image is sized proportionally.
percentag Sets the height and width as a percentage of the parent element
e If you only specify one value, the image is sized proportionally.
Adding a shadow to the image
You can use the box-shadow property to add a shadow to images.
img { box-shadow: 5px 5px 10px 10px #f00; }
You can specify the following options for the shadow:
Value Description
blur Amount (in pixels) of blurring around the shadow's
edge
color The shadow's color
offset- Horizontal offset (in pixels) of the shadow
x
offset- Vertical offset (in pixels) of the shadow
y
inset Specifies an inner shadow
spread Size (in pixels) of the shadow
0 – shadow is the same size as the element
Using an image as a border
You can use the border-image property to use an image as an element's
border.
border-image:url(diamond.png) 20 20 round;
The following properties can be used to specify border images for different
sides of the element:
border-top-image
border-right-image
border-bottom-image
border-left-image
Value Description
border-image- Path to the image
source
border-image-slice The image's height and width offset
border-image-width The image's width
border-image-outset The image's height
border-image-repeat Whether the image should be repeat or
stretch
Wrapping text to an image
You can use the float property to wrap text around an image.
CSS rule
.caution {
float: left;
margin-right: 10px;
}
Usage
<p><img class="caution" src="caution.jpg" />
caution caution caution</p>
The margin-left property can be used to add space between the image and
the text.
Placing of text on top of image
You can assign negative values to the position, top, and left properties to
position text on top of an image. If the version is below the picture, setting
its top property to a negative value will move the text on top of the film.
CSS rule
.overlap {
position: relative;
top: -200px;
left: 180px;
color: #ffffff;
}
Usage
<img src="sample.jpg" />
<p class="overlap">floating text</p>
}
You can also use CSS shorthand to specify borders:
img { border: 1px solid #000000; }
The examples above will add a border to all images. You can create a class
if you want to apply borders only to specified images.
.imgBorder { border: 1px solid #000000; }
<img class=“imgBorder” src=“sampleImage.jpg” />
Or, you can apply a border to all images inside a div tag:
CSS rule
#menuBar img { border: 1px solid #000000; }
Usage
<div id=“menuBar”><img src=“sampleImage.jpg” /></div>
Adding a drop shadow to an image
You can use Internet Explorer’s filter property to add a drop shadow to an
image.
img {
filter: progid:DXImageTransform.Microsoft.dropShadow (offX='3',
offY='5', color='#c0c0c0', positive='true');
}
The filter property was created by Microsoft and is not a part of the CSS
recommendation. It is only supported by Internet Explorer.
For more information about Internet Explorer filters, see “How do I use
Internet Explorer's filters?”
For other browsers, you can use the box-shadow property can be used to
add a drop shadow around an image. However, it will not add the drop
shadow inside transparent images.
img {
filter:alpha(opacity=50);
opacity:.50;
}
Removing link borders from an image
You can set an image’s border property to “0” to remove the border that
appears around image links by default.
img { border: 0; }
How do I zoom images when the user hovers over them?
You can use the hover pseudo class to change an image’s width and height.
First, wrap a link around the image:
<a href="javascript:void(0);">
<img src="clickstart.jpg" />
</a>
Then, specify the image’s width and height when the user hovers over the
image’s link:
a:hover img { width: 800px; height: 400px; }
In this example, the image will expand to 800x400 when the user hovers
over the image, and when the mouse moves from the image it will return to
its original size.
Making image expand on hover
You can use the transition property to make an image expand when the user
hovers over it and shrink when it loses focus. For example, you could
provide a "thumbnail" of an image that expands to full-size when the user
hovers over it.
CSS rule
.thumbTrans {
width: 50px;
height: 50px;
-moz-transition-property: width,height;
-moz-transition-duration: 4s;
-moz-transition-delay: 1s;
-webkit-transition-property: width,height;
-webkit-transition-duration: 4s;
-webkit-transition-delay: 1s;
-o-transition-property: width,height;
-o-transition-duration: 4s;
-o-transition-delay: 1s;
transition-property: width,height;
transition-duration: 4s;
transition-delay: 1s;
}
.thumbTrans:hover {
width: 100%;
height: 100%;
-moz-transition-property: width,height;
-moz-transition-duration: 4s;
-moz-transition-delay: 1s;
-webkit-transition-property: width,height;
-webkit-transition-duration: 4s;
-webkit-transition-delay: 1s;
-o-transition-property: width,height;
-o-transition-duration: 4s;
-o-transition-delay: 1s;
transition-property: width,height;
transition-duration: 4s;
transition-delay: 1s;
}
Making an image ‘pop-out’ on hover
You can use the hover pseudo class to rotate images and add a shadow.
img:hover {
box-shadow:1px 2px 5px #666666;
-moz-transform:rotate(5deg) scale(1.5);
-webkit-transform:rotate(5deg) scale(1.5);
transform:rotate(5deg) scale(1.5);
}
s you have followed this tutorial, you may have noticed that when you
change the size of text using CSS, there are a number of options.
You can see this for yourself in TopStyle.
Create a new style sheet, and click the "New Selector" button. Select the
"Simple" tab and select h1 from the HTML elements list. Next click the
"Add" button, followed by "OK".
There are two headers, one defined in absolute terms, and the other in
relative terms.
Older web browsers use to allow users to change the size of the fonts in
their browsers to:
- Largest
- Larger
- Medium
- Smaller
- Smallest
The problem was that any font size defined in absolute terms would not
increase in size because it was set in total measurements, and therefore
would always appear the same size on the screen. The font size defined in
relative terms would increase in size.
If you increased the font size to "Largest", you’d see the relative header
increase in size while the absolute header would stay at the same size.
To some extent, web browsers have taken away the functionality of absolute
measurements because they introduced a zoom feature instead of a font size
feature. This then magnified all text, absolute or relative, to the same
extent, throwing out some web designer's carefully designed layouts.
OK, let's consider the units for measurements, and what they represent.
The five absolute measurements are as follows:
1. cm - centimeters
2. mm - millimeters
3. in - inches
4. pc - picas (1/6 inch or 12 points)
5. pt - points (1/72 inch)
It should be noted that even if absolute measurements did work properly in
browsers with the new zoom features, they would only ever work as desired
if the browser knew the size of the screen, and the number of pixels the
screen displayed. In many cases, the browser would have to guess! This,
together with the more recent addition of zoom features, means that
absolute measurements aren't the best units to use when designing your
pages so that we won’t be looking into these.
It was important to mention absolute measurements in this book though,
because I am sure you will come across them when you are exploring the
CSS of your own (and other people's) web pages.
So relative measurements provide us with the best solution, especially when
we don't know what device the end user will be viewing the site on. For
example, nowadays they could be browsing on a computer, a tablet, a
Smartphone, or even some e-readers. With relative measurements, the font
sizes will be comparable to the size of the screen, and therefore give the
user the very best viewing experience.
Here are the relative measurements in some detail:
EX
The 'ex' is a measurement relative to the size of the font's lowercase 'x'. I
never use this measurement so that we won’t be looking at it in this book.
PX
The px is a relative measurement in screen pixels.
Pixels offer the designer the best control over layouts. You will see them
used a lot for things like borders, margins, padding, plus height and width
of screen regions when creating CSS layouts without tables.
What pixels are not recommended for is text size. Most modern browser
won’t have a problem, but some of the older ones won’t resize pixel-based
text.
Percentage
Percentage measurements are always relative to another value. For
example, if we want to increase the spacing between lines of a paragraph,
you can define the line-height as a percentage (it will be a percentage of the
font size).
Say for example we have: line-height: 150%. This will create a space
between the lines that is 150% of the font size. Therefore, if the font size is
10px, then the space between lines will be 15px. It is wise to define the
font-size in your CSS file if using percentages, otherwise results can be
unpredictable in the different browsers. This is because the font-size will be
taken from the web browsers default CSS file.
Here is an example showing line spacing using percentages:
(9.1.html and 9.1.css)
EM
The "em" is a relative measurement for the font size. Think of it as being
the size of a capital "M" to help you remember it, though that isn't entirely
accurate, but it is an excellent way to memorize it.
This is my preferred unit for defining text size. Because it's a measurement
relative to the font size, if we set a font-size of say 10px, then one em is
equal to 10px. 2 em would be similar to 20px, and 1.5 em would be 15 px.
To make this as easy as possible, it's a good idea to define the font size in
the style sheet as follows:
Create a new style sheet.
Click on the "New Selector" button, and then go to the "Simple" tab.
Select body from the HTML Element list, and then click the "Add" button
followed by "OK".
You'll see the following in your style sheet:
body {
}
Whatever properties you enter will be the default properties for all elements
on the page that appear between the <body></body> tags, i.e., everything.
I can define a default font-size like this:
body { font-size: 11px; }
This would make the default font size 11px. Here is a web page where I
have defined the default text size in this manner:
(9.2.html and 9.2.css)
In some older browsers, if you choose a larger font size, these sizes will
remain the same because we defined the default font as 20 px – an absolute
measurement. However, since most browsers now use the zoom feature,
this is less of a problem that it used to be. Nevertheless, just to be safe, we
are probably better off defining the default font-size this way:
body { font-size: 0.7em; }
This would make the default text size 70% of the default text size. So just
what is the default text size?
Well, every browser has its own default CSS that it uses to display web
pages. If you want to see what that size looks like in different browsers,
create a style sheet that sets the body text size to 1em.
body { font-size: 1.0em; }
Then create a web page with some text on it that uses the style sheet, and
view it in a few different browsers, or just look at 9.3.html and 9.3.css, as I
have done this for you.
Here is an excellent article on using em for sizing text. Richard Rutter uses
percentages instead of em to define the default font-size:
http://clagnut.com/blog/348
Chapter 12. CSS IDs and Classes
D selectors can only (or should only), be used ONCE on a web page, and
identify ONE item on the page.
By using an ID selector to reference two images on the page, I was breaking
a CSS rule. I should have used a CLASS instead.
ID Selectors and classes do mostly the same thing, BUT, an ID can only
be used once on the page, whereas types can be used multiple times.
Before we look at classes, let me give you an easy way to remember this:
Your ID refers to YOU and you alone. No one else can have your ID.
A class is a group of people so that a level can refer to multiple individuals.
Therefore, an ID is only used once, and a class can be used multiple times.
For this reason, we will use IDs for page elements that only occur once,
e.g., when we come to look at page layouts using CSS, we'll define IDs for
the page header area, the right and left margins, the main content section,
and the footer. These are obvious choices, since each of those sections only
occurs once per page.
We will use classes whenever we want to reuse a style on a page more than
once, for example, the alignment of images, font styling, and bullet points,
etc.
OK, we know that IDs and Classes can be used to override default display
properties, but we still haven't looked at how to create or use them yet. Let's
look at that now, so that you can start using them in your page designs.
ID Selectors
Start TopStyle and click on the "New Selector" button.
Switch to the "advanced" tab, and you will see a pair of radio buttons (aka
option buttons), labeled Class and ID.
Select ID, and then in the box underneath the radio buttons, type in a name
for your ID. I typed in "logo" for mine, since I am going to create the ID to
be applied to the logo on the page (it only appears once).
You will notice that as you type, TopStyle adds a '#' to the start of your ID.
Click the "Add" button (located above the radio buttons), and then click the
"OK" button on the bottom right. This will add this selector to your style
sheet.
In style sheets, the '#' symbol specifies that what follows is an ID. Here's
how mind looks:
#logo {
}
You can now add some styles to the ID in exactly the same way we have
done in other examples. I’ve added a few to mine, and here the finished
logo ID:
#logo {
font-size: 3em;
font-variant: small-caps;
font-weight: bolder;
background-color: Silver;
font-family: Verdana, Geneva, Arial, Helvetica, sans-serif;
}
The idea of this ID is to change the text properties in the logo area of my
page so that it is more extensive ("em" is a unit of measurement). My
sample here uses small caps, bold, has a silver background, and is the
Verdana, Geneva… font family. You probably knew this from seeing the
style sheet though, didn’t you?
You can see the effects of what this does to the page here:
You’ll notice that as you type, TopStyle adds a "." in front of the text you
are typing. In CSS, that "." specifies that whatever follows is a class.
OK, once done, click the "Add" button and then click "OK" to save the
changes to your style sheet.
he basis of the CSS layout is the box model since it directs the way in
which elements are shown and the way in which they associate with one
another. Imagine every element on the page as a rectangular box. Every box
is made of particular dimensions and takes up a particular measure of space.
The space the box occupies depends on the content in it, as well as the
margins and the padding borders around the content:
So, the
box model is what dictates the amount of space each element has on the
page. Now, let’s dive somewhat deeper into this idea by revising the main
components that constitute the CSS box model. Start thinking of each
HTML component on the page as a box. In fact, you can apply a global
style rule that will add a red outline to all the elements on the page. To do
this, simply add the following style rule to the top of the stylesheet:
*{
outline: 2px solid red;
}
This will add an outline to all the elements on the page and it will let us
easily visualize each of the items on the page as a box:
Once you have the dev tools panel open, in the elements tab on the left,
open up the header element and click on the h1 element. This will be the
element selected in the chrome dev tool and you will see the h1 highlighted
on the page:
Once the h1 element is selected, you can increase the width of the styles tab
on the right and scroll down until you see the box model for the h1:
As you can see from the above screenshot, the h1 element’s box model can
be seen clearly. We have a default margin applied to the top and bottom,
and it has no border or padding. Hopefully, this will give you a better
understanding of how each element on the page is represented, and how
they interact with each other based on their display type.
Chapter 14. Step By Step Addition Of CSS To HTML
Document
The Three Ways To Add CSS To An HTML Document
ou may recall from your HTML knowledge that there are three ways to add
CSS to an HTML document: as inline style, as an internal style, and as a
link to an external stylesheet. In this the book internal style method will be
used because it more easily demonstrates, for learning purposes, how CSS
relates to HTML in a single screen window and when using short
economical code snippets. However, normally you will want to be using
CSS script in external style sheets, since that is the generally preferred
method. Also for visual clarity, many redundant elements will be omitted,
such as <!DOCTYPE html>, <html> and <body>. Just assume that, if these
examples were used on real web pages, you would have all the requisite
elements in place.
For review, let’s just remind ourselves of the syntax and method for each
manner of adding CSS to an HTML document.
Inline Style
Inline CSS is presented within the opening HTML tag, where style is a
Global Attribute that can be used by any HTML element. The value of any
applied style attribute is a property:value pairing declared inside of
quotation marks, attached to the attribute through the assignment operator
equal sign, = . Every property:value pairing should end in a semi-colon, and
similarly when combining more than one inline style, each property: a
semicolon should separate value pairing.
Before Cascading Style Sheets, a vast amount of work was entailed by
having to style every HTML element individually. Any change of a style
decided later on meant that each element that had the style had to be
manually adjusted. Here’s an example of inline CSS as part of an HTML
text file:
<h1 style="color:red; font-style:italic; font-weight:100;">Red Heading
Typography</h1>
Above three styles have been applied, making the font color red, its
style italic, and the font weight 100 (on a 9-item scale 100 to 900– note that
not all fonts support all nine available CSS weights).
Internal Style
With internal CSS, the style is placed inside the <head> section of the
HTML document, which is always above the <body> section, you will
recall. This method is internal to the HTML document, i.e. a single web
page, as a whole, rather than specific to a single element, which is why it is
called internal. The CSS is applied within the <style> HTML opening and
closing tags instead of a style attribute declaration and is declared in the
standard CSS format. The basic CSS syntax is:
s {
property : value;
property: value;
}
The “s” above stands for “selector”, which is any HTML element (in this
context, “s” is not the HTML tag for “strikethrough!”). With internal CSS,
the property:value pairs are declared within curly braces, { }, instead of
quotation marks. The property:value pairs taken together with the curly
braces make up a declaration in CSS. At a high level, the syntactical
construct can be understood as:
Selector {Declaration} {Declaration} {Declaration}
Selector {Declaration} {Declaration}
And each declaration in turn is made up of:
{property:value; property:value; property:value;}
{property:value; property:value;}
etc.
A selector and its declaration(s) together make up a rule set:
rule set = selector {declaration(s)}
To ground this syntax in a typical example, let’s look at the use of multiple
declarations applied to a single selector. Note that sometimes the order of
declarations has no effect on the visual result, but in other cases the order
does have an effect.
<style>
h2 {
text-align: center;
font-family: cursive;
color: orange;
}
</style>
<h2>
Hi, I've been styled.
</h2>
External Stylesheet
Well-developed styles are made up of many lines of code, and for this
reason it is usually impractical to create too many style statements as
internal CSS within the <head> area of an .html document. Instead, CSS
code is usually placed in its own text file(s) that have the file extension .css.
This external style is then linked to in the <head> of an .html document via
a <link> element. This link to the external .css file will instruct the browser
to obtain the styling information from the external file first before
continuing to load, and style, the subsequent HTML content. When using
code editors to write CSS les, make sure you set the file’s syntax to CSS,
though many editors will automatically detect the language you are writing
in. When you save the file, make sure it has the .css file extension so that it
is usable as a style sheet for a browser.
<html>
<head>
<link rel="stylesheet" href="css.css" type="text/css">
</head>
<body>
</body>
</html>
Above, we define the relationship (the rel attribute in <link>) between the
.html document and the external resource as a stylesheet relationship. The
URL to locate the external style sheet is a relative URL path– in this
example, the CSS file is in the same directory as the index.html document.
As your websites become more complex, you will eventually want to have
your CSS source code files in their directories or folders, in which case the
URL in the href might instead be “CSS/css.css” or “scripts/css.css” and so
on. These forward slashes indicate that the .css file is to be found inside of a
directory called “CSS” or “scripts,” and that these directories are in the
same directory as the .html file. Finally, the Media Type of the stylesheet is
declared with the type attribute. CSS, like all source code, is always just a
text file, but instead of the usual .txt file extension used for text files, .css is
used so that the browser knows to parse the code as containing styling
information.
Placing the .css file in the same directory as the .html file, OR alternately, in
a scripts directory. The value of the href attribute has to specify the path
needed to find the external style document.
Chapter 15. Introduction To JavaScript
TML is used to develop web pages, and web pages can become complex
documents that define the content of a page. Materials produced using
HTML can get CSS added to it, and done in different ways like attaching a
background color, changing font sizes, image size, typeface, shadow, colour
intensity, and so on. HTML and CSS can be used to attain a static beauty of
a web page. With JavaScript, you can inject life into web pages using
JavaScript effects such as form validation, modal, slider, pop up, and so on.
The practice of developing web pages or applications with HTML, CSS,
and JavaScript is called Frontend development, and it enhances the user’s
interaction with web pages. JavaScript is a well-built client-side scripting
language. JavaScript is also generally used for mobile and game application
development.
A Brief History of JavaScript
· 1995: While working at Netscape, "LiveScript" was created by
Brendan Eich and later renamed to "JavaScript."
· 1996: Javascript released by Microsoft, a port, for IE3.
· 1997: JavaScript became standardized in the "ECMAScript" spec.
· 2005: "AJAX" was coined, and the web 2.0 age began.
· 2006: jQuery 1.0 was released.
· 2010: node.JS was released.
· 2010: angular.JS was released.
· 2012: ECMAScript Harmony spec nearly finalised.
Several programmers tend to believe that JavaScript and Java belong to the
same category, and this opinion is false because Java and JavaScript are
different from each other. Java is a sophisticated programming language,
while JavaScript is a scripting language only. The C programming language
influences the JavaScript Syntax.
What does the future hold for JavaScript?
The technologies of HTML5 and JavaScript can be used to create
extensions for Windows 8 desktop widgets, browsers, Chrome OS, and
Firefox OS applications. A large number of non-web related applications
also adopt the scripting language of JavaScript, and it can be used to create
HTML templates (Mustache), attach activities to PDF documents, database
interaction (MongoDB), and also control (Cylon.js). JavaScript has a bright
future because web platforms continue to mature and advance its usage
beyond only browsers. This scripting language will remain an integral part
of future developments.
How to Run JavaScript?
JavaScript is a scripting language that cannot run on its own. The browser
does the code running of JavaScript. When a user requests an HTML page
that contains JavaScript, the browser receives the script, and then the
browser gets to decide its execution. All modern browsers support
JavaScript, which is a massive advantage for the scripting language.
JavaScript also runs on operating systems like Linux, Mac, and Windows.
Requirements to Learning JavaScript
● Basic knowledge of HTML and CSS
● A text editor
● A browser
● Logical thinking and tenacity
Programming
Computer programming is the act of implementing and creating a different
set of rules to allow a computer to perform a specific task. It is the process
of speaking the computer language, which involves picking an algorithm
and encoding it into a notation so that the computer can get it executed.
Types of Programming Languages
1. Low-level language
• Machine code
• Assembly language
2. High-level language
Inscribed in different languages such as Java, PHP, C, C++, JavaScript, C#,
Python, etc. Computer programs can be either interpreted or compiled
language, although JavaScript is an excellent example of Interpretation.
Keeping Them Separate
HTML: It defines the page content.
CSS: It determines the content’s presentation.
JavaScript: It controls content characters.
When these technologies are used in developing a web page, they must be
stored differently.
1. Create a separate .html file for HTML
2. Create a separate .css for CSS
3. Create a separate .js for JavaScript
The Wrong Approach
<p>
Whatever you do, <a href="666.html" style="color: red;" onclick="alert('I
said dont
click')">don't click this link</a>!
</p>
The Right Approach
<p>
Whatever you do, <a href="666.html" id="warning">don't click this
link</a>! </p>
<style>
#warning{
color:red;
}
</style>
<script>
var warningLink=document.getElementById("warning");
warningLink.addEventListener('click',alerter, false);
function alerter(){
alert("I said don't click");
}
</script>
The best approach is to save the style and script into a separate .css file and
.js file and unite them via link tag and script tag in the HTML document.
This approach is utilized in this manual.
<link rel="stylesheet" href="warning.css" /> <p>
Whatever you do, <a href ="666.html" id="warning">don't click this
link</a>!
</p>
<script src="warning.js"></script>
JavaScript Basics
Statements
The JavaScript syntax is also known as a C-style syntax which is related to
the syntax used by PHP. A JavaScript program consists of JavaScript
language construct, command, and keyword. This manual will teach you
how to develop amazing things with the use of JavaScript language
constructs, command and keyword. Every statement must end with a
semicolon or a new line. By popular convention a JavaScript programmer
should write one statement per line and with a semicolon at the end.
document.write('Hello World') document.write('Here comes the
JS Engineer')
document.write('Hello World'); document.write('Here comes the JS
Engineer');
document.write('Hello World');
document.write('Here comes the JS Engineer');
Comments
These are human-readable texts which the computer disregards. JavaScript
consists of two types of comments:
//This is a single line comment
/*
This is a multiple line comment on line one
This is a multiple line comment on line two
This is a multiple line comment on line three
*/
Variable
To declare a variable, Use the “var” keyword.
A variable is used to store data and references the memory location in
computer memory (RAM.) A variable can perform 3 actions, and they are:
1. Declaring the variable
2. Inserting data inside the variable
3. Getting the data into the variable
It is important to name a variable to enable easy differentiation. Few rules
guide naming variables.
Variable naming rules
● They consist of the following character; numbers, letters, dollar signs
or underscores but a number cannot be the first character
● Variables are case sensitive, therefore ‘number-one’ differs from
‘NumberOne.’
● Variables cannot be JavaScript reserved words
● Variables select meaning and clarity
● Variables do not hold space variable that creates more than a word,
therefore ‘number one’ is written as ‘numberone’ but for easy
readability ‘numberone’ is often written as ‘number_one’ or
‘numberOne.’
● Select a naming convention and become accustomed to it.
var 2numberOne; //invalid variable name because it started with number
var numberOne!; //invalid variable name because it contains a non-
permitted character!
var x; //valid variable name but not descriptive
var numberOne; //variable declaration
var numberTwo; //variable declaration
numberOne=5; //assigning data to variable
numberTwo=10; //assigning data to variable
document.write(numberOne); //calling data inside a variable
document.write(numberTwo); //calling data inside a variable
var numberOne=3; //variable declaration and assignment
var numberOne, numberTwo, numberTwo; //multiple variable declaration
var numberOne=2, numberTwo=4, numberTwo=6; //multiple variable
declaration and assignment
Chapter 16. JavaScript Syntax
e finally start to see JavaScript source code! So far everything we have seen
in this manual may have seemed very theoretical, but from now on we hope
you find it more enjoyable to start seeing more practical and directly related
to programming.
The JavaScript language has a syntax very similar to Java because it is
based on it. It is also very similar to that of the C language, so if the reader
knows any of these two languages it will be easy to handle with the code
Comments in The Code
A comment is a part of code that is not interpreted by the browser and
whose utility lies in making it easier for the programmer to read. The
programmer, as he develops the script, leaves individual phrases or words,
called comments, which help him or anyone else to read the script more
easily when modifying or debugging it.
Some JavaScript comments have been seen previously, but now we are
going to count them again. The language has two types of comments. One
of them, the double bar, is used to comment on a line of code. The other
comment can be used to comment on several lines and is indicated with the
signs / * to start the comment and * / to end it. Let's see some examples.
<SCRIPT>
// This is a one-line comment
/ * This comment can be extended
along several lines.
The ones you want * /
</SCRIPT>
Upper Case and Lower Case
In JavaScript uppercase and lowercase letters must be respected. If we
make a mistake when using them, the browser will respond with an error
message, either syntax or indefinite reference.
For example, the alert () function is not the same as the Alert () function.
The first displays text in a dialog box, and the second (with the first capital
A) simply does not exist, unless we define it ourselves. As you can see, for
the function to recognize JavaScript, you have to write all lowercase. We
will see another clear example when we deal with variables, since the
names we give to the variables are also case sensitive.
As a general rule, the names of things in JavaScript are always written in
lowercase, unless a name with more than one word is used, since in this
case the initials of the words following the first will be capitalized. For
example, document.bgColor (which is a place where the background color
of the web page is saved), it is written with the capital "C", as it is the first
letter of the second word. You can also use capital letters in the initials of
the first words in some cases, such as the names of the classes.
Separation of Instructions
The different instructions that our scripts contain must be conveniently
separated so that the browser does not indicate the corresponding syntax
errors. JavaScript has two ways of separating instructions. The first is
through the semicolon (;) character and the second is through a line break.
For this reason, JavaScript statements do not need to end with a semicolon
unless we put two instructions on the same line.
It is not a bad idea, anyway, to get used to using the semicolon after each
instruction because other languages such as Java or C force them to be
used and we will be getting used to making a syntax more similar to the
usual one in advanced programming environments.
Variables in JavaScript
This is the first of the articles that we are going to dedicate to variables in
JavaScript within the JavaScript Manual. We will see, if we do not already
know, that variables are one of the fundamental elements when making
programs, in JavaScript as well as in most of the existing programming
languages.
So let's start by getting to know the concept of a variable and we'll learn
how to declare them in JavaScript, along with detailed explanations of their
use in the language.
Variable Concept
A variable is a space in memory where data is stored, an area where we can
store any type of information that we need to carry out the actions of our
programs. We can think of it as a box, where we store data. That box has a
name, so that later we can refer to the variable, retrieve the data as well as
assign a value to the variable whenever we want.
For example, if our program performs sums, it will be very normal for us to
store in variables the different addends that participate in the operation and
the result of the sum. The effect would be something like this.
adding1 = 23
adding2 = 33
sum = adding1 + adding2
In this example we have three variables, adding1, adding2 and sum, where
we save the result. We see that their use for us is as if we had a section
where to save a data and that they can be accessed just by putting their
name.
Rules for Variable Naming in JavaScript
Variable names must be constructed with alphanumeric characters (numbers
and letters), the underscore or underscore (_), and the dollar character $.
Apart from this, there are a number of additional rules for constructing
names for variables. The most important is that they cannot start with a
numeric character. We cannot use rare styles such as the + sign, a space, or
a - sign. Supported names for variables could be:
Age
country of birth
_Name
$ element
Other $ _Names
We must also avoid using reserved names as variables, for example we will
not be able to call our variable words like return or for, which we will see
that they are used for structures of the language itself. Let's now look at
some variable names that you are not allowed to use:
12 months
your name
return
for
more or less
pe% pe
Variable Names in JavaScript Are Case Sensitive
Remember that JavaScript is a case-sensitive language, so variables are also
affected by that distinction. Therefore, the variable named "myname" is not
the same as the variable "myName". "Age" is not the same as "age".
Keep this detail in mind, as it is a common source of code problems that are
sometimes difficult to detect. This is because sometimes you think you are
using a variable, which should have a specific data, but if you make a
mistake when writing it and put upper or lower case where it should not,
then it will be another different variable, which will not have the expected
data. Since JavaScript does not force you to declare variables, the program
will run without producing an error, however, the execution will not provide
the desired effects.
Declaration of Variables in JavaScript
Declaring variables consists of defining, and incidentally informing the
system, that you are going to use a variable. It is a common custom in
programming languages to explicitly specify the variables to be used in
programs. In many programming languages there are some strict rules
when it comes to declaring variables, but the truth is that JavaScript is quite
permissive.
JavaScript skips many rules for being a somewhat free language when
programming and one of the cases in which it gives a little freedom is when
declaring the variables, since we are not obliged to do so, contrary to what
happens in other programming languages like Java, C, C # and many
others.
Variable Declaration with Var
JavaScript has the word "var" that we will use when we want to declare one
or more variables. Not surprisingly, that word is used to define the variable
before using it.
Note: Although JavaScript does not force us to declare variables explicitly,
it is advisable to declare them before using them and we will see from now
on that it is also a good habit. In addition, in successive articles we will see
that in some special cases, a script in which we have declared a variable and
another in which we have not, will not produce exactly the same results,
since the declaration does not affect the scope of the variables.
var operand1
var operand2
You can also assign a value to the variable when it is being declared
var operand1 = 23
var operand2 = 33
It is also allowed to declare several variables on the same line, provided
they are separated by commas.
var operand1, operand2
Declaration of JavaScript Variables with Let and Const
From Javascript in modern versions (remember that JavaScript is a standard
and that as it evolves over time), specifically in Javascript in its ES6
version, there are other ways to declare variables:
Let declaration: This new way of declaring variables affects their scope,
since they are local to the block where they are being declared.
Const Declaration: Actually "const" does not declare a variable but a
constant, which cannot change its value during the execution of a program.
Perhaps at this point in the Javascript manual it is not necessary to delve too
deeply into these declaration models and for those who are learning we
recommend focusing on the use of declarations with "var". However, if you
want to have more information about these new types of variables, we
explain them in the article Let and const: variables in ECMAScript 2015. If
you want to see other news about the Javascript standard that came in 2015,
we recommend reading the ES6 Manual.
Chapter 17. Definition of Arrays in JavaScript
This may not make a lot of sense right now, but we are going to expand
upon it a bit and see more about what we will be able to do with these
arrays and the different parts that come with it. Before we move into this
though, we need to take some time to talk about some of the array methods
that are important to our code. There are a lot of different ways that happen
with our object of an array, so let’s take a look at what all of these mean.
As we can see here, there are a lot of possibilities that we can work with
when it comes to handling the arrays that show up in our codes. These
arrays are going to help us to hold onto some of the data that we have more
efficiently and will ensure that we can put it all together and pull out the
elements that we need and want without a lot of struggle along the way.
Make sure to take a look at some of the methods and functions available
with these arrays, especially with JavaScript, so you know how to use them
for some of your own needs as well.
Chapter 18. What to Do Next?
reating a web page is something that has been wreathed in mysticism and
cyber mumbo jumbo for years, but I hope that I’ve shown you that it’s not
as scary as you might think. In fact, HTML is actually fairly straight
forward. If you’re looking for a hobby that can really accomplish something
and is easy to explain, then you’ve come to the right place. These are the
foundations for you to build your web page and push on to greater things
like CSS, Java, JavaScript, C++, and the list goes on and on. Remember,
that you can never really get in over your head if you master and truly
understand what it is that you’re working on in the moment.
If something doesn’t make sense to you or is confusing, my best suggestion
to you is to open up your TextEdit or Notepad and start working on it. Pull
it up in your browser and have a look at what it does for your page. Taking
everything step by step will inevitably lead you to the path of success.
There is never a reason to jump ahead without fully understanding what it is
that you’ve done.
All of these programming languages are quite vast in their own right.
However, since they are also simple and easy, you should not have too
much of a problem mastering them. With hard work and a bit of time, you
will be able to create full-fledged websites in no time at all. The concepts
will help you understand and apply the different scope of variables, invent
types, loops and arrays, form structure, positioning, and so on.
Of course, this book should have given you enough to have a good base for
all three languages. You should have already seen the hello world examples
and noted how easy they are. As such, you should have no problems with
the basic syntax for each language.
You will have come across the basic functions, statements, and tags that are
commonly used in these languages. More importantly, you should no longer
have any problem using them in a web page of your creation.
In HTML, you came to know how a simple web page can be written and
filled with content. Then, with CSS, you will have been able to stylize that
web page and make it look attractive. Finally, JavaScript allowed you to
make your web page more interactive. As such, your web page should now
be looking and feeling a lot like the web pages you have previously
admired.
As we get to the end, you have learned quite a lot about web development,
and you learned the creation of functional and well-structured HTML
documents as well as styling, color usage, layouts, and typography using
tags. Practice what you have learned because practice is the best way to
learn.
With everything that I have presented to you, you should be able to get the
grasp on the beginnings of a web page and if you can get the beginning, it’s
just a matter of taking the next step piece by piece. So good luck and get out
there and make an amazing web page.
I hope you have learned something!