[go: up one dir, main page]

100% found this document useful (2 votes)
312 views227 pages

Coding Languages For Absolute Beginners 6 in 1

Uploaded by

Rahul Bhan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (2 votes)
312 views227 pages

Coding Languages For Absolute Beginners 6 in 1

Uploaded by

Rahul Bhan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 227

CODING

LANGUAGES
for
Absolute Beginners
© Copyright 2018 by ___Zach Webber _- All rights reserved.
The following book is reproduced below with the goal of providing information that is as accurate and
reliable as possible. Regardless, purchasing this book can be seen as consent to the fact that both the
publisher and the author of this book are in no way experts on the topics discussed within and that any
recommendations or suggestions that are made herein are for entertainment purposes only. Professionals
should be consulted as needed prior to undertaking any of the action endorsed herein.
This declaration is deemed fair and valid by both the American Bar Association and the Committee of
Publishers Association and is legally binding throughout the United States.
Furthermore, the transmission, duplication or reproduction of any of the following work including specific
information will be considered an illegal act irrespective of whether it is done electronically or in print. This
extends to creating a secondary or tertiary copy of the work or a recorded copy and is only allowed with an
express written consent from the Publisher. All additional rights reserved.
The information in the following pages is broadly considered to be a truthful and accurate account of facts
and as such any inattention, use or misuse of the information in question by the reader will render any
resulting actions solely under their purview. There are no scenarios in which the publisher or the original
author of this work can be, in any fashion, deemed liable for any hardship or damages that may befall them
after undertaking information described herein.
Additionally, the information in the following pages is intended only for informational purposes and should
thus be thought of as universal. As befitting its nature, it is presented without assurance regarding its
prolonged validity or interim quality. Trademarks are mentioned without written consent and can in no way
be considered an endorsement from the trademark holder.
TABLE OF CONTENTS

ARDUINO
The Ultimate Beginner's Guide to Learn and Understand Arduino
Programming Effectively
Introduction
Chapter 1 : Syntax / Variables / Constants
What is a program/sketch?
Arithmetic Operators
Comparison Operators
Boolean Operators
Arduino Programming Syntax
Variables
Constants
Digital Input/Output Functions
Analog Input/Output Functions
Chapter 2 : Our First Program
Chapter 3 : Logic Statements
Chapter 4 : For Loops
Chapter 5 : Arrays
Chapter 6 : Logical Switches
Chapter 7 : User Defined Functions
Chapter 8 : Best Practices
Comments
Coding Best Practices
More Naming Best Practices
Conclusion
C++
The Ultimate Beginner’s Guide to Learn and Understand C++
Programming Effectively
Introduction
Chapter 1 : What Is C++?
The history of C++
Why do programmers use this language?
Chapter 2 : How to Work on Your First Program
C++ compilers
Basic syntax
Chapter 3 : The Syntax of C++
Program comments
Data types
Why is it so important to start new lines in C++?
Functions in C++
Modifier Types
Exception handling
Chapter 4 : Variables and More in C++
Defining the variables
Chapter 5 : Arrays and Loops
Arrays
Working with loops
‘While’ loop
‘For’ loop
Nested loops
Chapter 6 : The Importance of Operators in C++
Logical operators
Arithmetic operators
Assignment operators
Relational operators
Chapter 7 : Decision Control in C++
Switch statements
The ‘if’ statements
The ‘if’ else statements
The ‘elif’ statements
Conclusion

C#
The Ultimate Beginner's Guide to Learn and Understand C#
Programming Effectively
Introduction
Chapter 1 : The Basics of C#
What is special about C#?
What do I need to get started?
Getting started with the C# language
Writing out a program with C#
Analyzing the program
Comments in C#
Chapter 2 : Variables and Types of the C# Language
Data types
Variables
Creating an identifier
Chapter 3 : Working with Operators
Arithmetic operators
Assignment operators
Relational operators
Logical operators
Bitwise operators
Chapter 4 : How to Create Your Own Conditional Statements
The ‘if’ statement
The ‘if else’ statement
What are nested conditional statements?
Chapter 5 : Creating Objects and Making Them Work
Classes and Objects
What is OOP?
Objects
Classes
How to use these classes in your code
How to create your own objects
Creating the object
System classes
How to assign a parameter to the object
Releasing your objects
The constructors
Chapter 6 : How to Define Classes with the Help of C#
The basics of working with classes
Components of classes
Methods
Custom classes
How to organize your classes
Accessing the classes
A final word about classes
Conclusion

POWERSHELL
The Ultimate Beginner's Guide to Learn and Understand
PowerShell Programming Effectively
Introduction
Chapter 1 : What Is the PowerShell Language?
What is PowerShell?
What are the things that can I do with PowerShell?
The benefits of working with PowerShell
Chapter 2 : How to Create Your Own Commands in PowerShell
How does the help command work?
Concepts help
Aliases
Chapter 3 : Outputs and Pipelines in PowerShell
How to work with pipelines
How to work with format output
How to control the output
How to set the output
Chapter 4 : The Operations and Wildcards
Operators that work for comparison
What are the wildcards?
How to work with logical operators
Arithmetic operators
Chapter 5 : Working with Strings and Quotes in PowerShell
String values
How to add in special characters
System_String object members
Chapter 6 : The Drives and Providers
The PowerShell Providers
What are the built-in drives?
How to create your own drive
Conclusion

PYTHON
The Ultimate Beginner's Guide to Learn and Understand Python
Programming Effectively
Introduction
Chapter 1 : What Is Python and Why Is It a Good Programming Language
to Learn?
Why should I learn Python?
Download Python
The basics you should know about Python
The keywords
How to name the identifiers
Statements
Comments
Functions
Working with variables
Chapter 2 : Classes and Objects
How to create a new class
Class definition
Special attributes
How to access members of a class
Chapter 3 : Conditional Statements in Python
How to work with ‘elif’ statements
Chapter 4 : Inheritances to Clean Up the Code
How to override the base class
Overloading
Final notes about inheritances
Chapter 5 : How to Work with Exceptions in the Code
How to raise an exception
How to define your own exceptions
Chapter 6 : The Value of Loops
The ‘while’ loop
The ‘for’ loop
The ‘nested’ loop
Conclusion

SQL
The Ultimate Beginner's Guide to Learn and Understand SQL
Programming Effectively
Introduction
Chapter 1 : The Basics of SQL
What is SQL?
How this works with your database
Relational databases
Client and server technology
How to work with databases that are online
Why is SQL so great?
Chapter 2 : The Commands That You Should Learn
Data definition language
Data manipulation language
Data query language
Data control language
Data administration commands
Transactional control commands
Chapter 3 : The Different Data Types That Work in SQL
Characters that are fixed in length
Variable characters
Numeric values
Literal strings
Boolean values
Chapter 4 : How to Manage Objects
What is the schema?
How to create a new table
How to create a table with one that already exists
How to drop tables
Chapter 5 : How to Do Your Own Search Results Through SQL
How to create a new query
How to work with the SELECT command
How does case sensitivity work?
Conclusion
ARDUINO

The Ultimate Beginner's Guide


to Learn and Understand Arduino
Programming Effectively
Introduction
Congratulations on purchasing, Arduino: The Ultimate Beginner's Guide to Learn
and Understand Arduino Programming Effectively, and thank you for doing so.
Welcome to this beginner's guide to effective programming for the Arduino
microprocessor. In this book you will learn the fundamental programming skills
you will need to read and write your own Arduino sketches in no time. While
this book assumes the reader is brand new to programming, it does assume the
user has some knowledge or skills of the hardware components of their Arduino
kit. If you are unfamiliar with the hardware, I strongly suggest you familiarize
yourself with that now, as the discussion of things like ‘pins’ will make a lot
more sense if you understand what that means for your circuit design.
For the purposes of this book, we will be assuming you are using the Arduino
Uno. However, the lessons in this guide are not hardware specific. The only
difference with other hardware is that the pins may be different for certain pin
specific functions, such as pin 13 being for the built-in LED on the Arduino
Uno.
There are plenty of books on this subject on the market, so thanks again for
choosing this one! Every effort was made to ensure it is full of as much useful
information as possible, please enjoy!
Chapter 1

Syntax / Variables / Constants

What is a program/sketch?
For this book when we talk about a program, we are speaking about the lines of
code that get uploaded onto your Arduino microprocessor, and the instructions
they provide to the chip. Arduino uses what is known as a ‘human-readable’
code. This is a fancy way of saying that the programming language uses English
words and is formatted to be understood by a human.
The words don't actually mean anything to the computer, however, so there is
another step that needs to take place to convert the human readable code into
machine code. This process is known as ‘compiling’ and is somewhat
complicated when you get into what is actually happening behind the scenes.
Thankfully the Arduino IDE, or ‘Integrated Development Environment,’ comes
with a built-in compiler and will do it for us at the push of a button. Arduino
calls up pieces of code sketches, and they are created within the Arduino IDE,
before uploading them onto your Arduino board with a push of a button after the
program is compiled. Each sketch has a few bare minimum requirements to
compile and load onto the chip successfully. The bare minimum elements of a
program are the following lines of code:
void setup () {
// initial setup code run once
}
void loop () {
// main program instructions run repeatedly
}
If you don't understand what any of those words mean right now, that's perfectly
fine. The only thing that’s important right now is that your sketch must contain
at least that much information to be a valid program, anything less is not a valid
sketch. You will be taught what all of the elements mean in a later portion of
this book.
Now that we know the minimum requirements for a sketch, let's start getting into
the details.
Arithmetic Operators
= (assignment operator)
+ (addition)
– (subtration)
* (multiplication)
/ (division)
% (modulo)
^ or e (exponent)

For those who are wondering if the modulo will calculate the remainder of a
calculation. Look at this example:
n = 9%4 // n is 1
n = 9%5 // n is 4
n = 7%5 // n is 2
n = 3%3 // n is 0

This can be very useful to contain your dataset within a certain range.

Comparison Operators
These are the operators you use in the code to compare variables against each
other:
== (equal to, as in are these two variables equal)
!= (not equal to, as in are these two variables not equal to
each other)
> (greater than)
>= (greater than or equal to)
< (less than)
<= (less than or equal to)

Boolean Operators
&& (and)
|| (or)
! (not)

Boolean operators are used to execute conditional logic when you want to
compare more than one condition at a time.

Arduino Programming Syntax


When it comes to programming languages, you can think of syntax as the
grammatical rules that make up that language. Just like in natural languages like
English that uses grammatical elements such as commas, semi-colons, and
periods to express information to the reader, so too do programming languages.
The syntax is the component which conveys similar information to the compiler
about the context of the code. Let's take a look at an example to see the
comparison. This sketch can be found in the Arduino IDE through the following
path:
File → Examples → 01.Basics → ReadAnalogVoltage
Okay so a lot is going on here, so before you get overwhelmed, we're only going
to focus on a few elements of this block of code. I'd like to draw your attention
to what's known as ‘comments.’ In programming, it's very important to write
comments about what you are thinking about when you write a certain piece of
code. This helps not only your future-self in understanding your thought process
when you wrote it, but importantly, other coders as well. Your sketch should be
as easy to read and as much as possible, easy to understand. Comments go a long
way to making sure that's the case. There are two kinds of comments in Arduino
programming: ‘block’ comments, and ‘line’ comments.
Block comments are for a paragraph of text, usually, at the start of a sketch, that
describes the purpose of the sketch or an important concept of the code in detail.
In our example, the block comment is the large gray block of text at the start of
the sketch. The block comment is indicated to the compiler with a pair of
symbols that correspond to the start and end of the comment.
To open a block comment, we use ‘/*’ and ‘*/’ is used to show the end of the
block. These tags tell the compiler to ignore everything after the opening tag
until the ending tag is encountered.
For a shorter single line comment, ‘//’ will tell the compiler to ignore the rest of
that line. It will ignore everything until the next time you press ‘return.’ If you
intend to write multiple sentences in your comment for clarity, it is better to use
block commenting. Use the ‘//’ style comments to explain shorter simple ideas
in your code. In our example code, the programmer has given us plenty of
comments to know what they are doing with each element. Even if you don't
fully understand the programming code, these comments tell you what each part
of the program is doing.
In the example, we can see that that ‘setup’ only runs once, and within that
space, we will initialize serial communications at 9600 bits per second. Pretty
technical, but importantly it is clear what the intention of this code is for other
readers such as ourselves.
Throughout the comments, we see that loop will run forever, and it makes up the
bulk of the instructions that the program executes. The statement int
sensorValue = analogRead(A0), is pretty complicated and it really is not that
intuitive at first glance. But again, thanks to our comments, we know from the
line above it that this line of code is reading the input on analog pin 0.
The last lines of code, again, are explained nicely to us telling us that some math
conversion is taking place, and then it is simply printing the results so it can be
read. When you write your own programs, try to think ahead and create
effective comments to make it easier for anyone to understand what you are
doing with that code.
The next element to learn about is all those semi-colons you see happening in the
block of code. In this programming language, you can think of semi-colons like
you would think of periods in a normally written sentence. A semi-colon in a
sketch tells the compiler that it has reached the end of a particular instruction. If
you forget to add a semi-colon, the sketch won't compile properly, and you will
get an error until you put it in. Now, you may wonder if that's the case why
doesn't every line end in a semi-colon? We will cover those brackets () and curly
braces {} next.
Let's next discuss curly braces. Curly braces indicate to the compiler that
everything contained within them relates to the function before it. We will
discuss functions in a later chapter, but for now know that both void setup () {}
as well as void loop () {} are both functions, and the code written in between the
curly braces are the instructions that define them. What does that mean exactly?
Let's use void loop () {} as an example. This is actually the main body of the
program you’re writing. As the name implies, it will run in a loop over and over
again. Doing what exactly? The instructions you want to provide it will be
placed between the curly braces. In our example above, it will read the value on
analog pin 0, convert it to a value between 0V and 5V, and then display the
results on a serial monitor.
Brackets serve two uses depending on the context they are used. The simplest
use of them is in a mathematical expression, where they take the same context as
in math: execute the calculation in the brackets first before resolving the rest of
the calculation, simple and easy. The more complex use of brackets is to provide
what is known as ‘parameters’ to a particular function or method. We will
discuss methods with a more detailed explanation in the later chapters. For now,
all you need to do is to understand that it is essentially a tool that can perform a
specific task.
Let's look at the function, Serial.begin(9600); as an example. Here we are using
the Serial.begin tool to tell the compiler to turn on the serial communications
hardware. However, this function needs more information to do what we are
asking it to do. It needs to know what bandwidth to use to transmit that data
first. We give it the information needed by putting it in the function's parameters
or within the braces that follow it. In our case above, we are saying that it needs
to transmit at 9600 bits per second.
Using the above example as a guide, we can take a guess at what's going on with
the line Serial.println(voltage) as well. This is telling the compiler, ‘Okay print
voltage through the serial communications port with information (voltage).’
Does this mean the screen will just display the word ‘voltage’ over and over
again? Actually no, because in this case ‘voltage’ as used here is what's known
as a variable, and is a placeholder that points to data that varies . There are
several different kinds of variables, and it is the element of the code we will be
discussing in our next chapter, now that you have a basic understanding of the
grammar or syntax of Arduino sketches.

Variables
In programming languages, variables are like bookmarks keeping track of the
important details in a book. In a program, these details can be things like the
number of times you have gone through a loop, the number corresponding to a
pin on your Arduino, a word, or the result of a calculation you just did. Those
are a lot of different kinds of information to keep track of. There are also
different kinds of variables suitable for different purposes. We will introduce
and explain these elements here.
Regarding Arduino variables, there are so many variables that each has a
specific purpose. We will go over the most common ones now. Integers are the
most common kind of variable, and they can hold a signed number from -32768
to 32767. They are represented by the abbreviation int . Boolean variables are
for dealing with Boolean logic and contain true or false. They have been given
the abbreviation bool . For single letters or numbers as a character on a page,
char is the abbreviation used to distinguish that type. ‘Word,’ as it suggests, is a
placeholder for several characters of a word's length. When dealing with
‘floating point’ numbers or numbers with decimals, the ‘float’ variable is
appropriate. There are more than just these types here, but they are less
common. The only other data type worth mentioning is ‘void’ which is a lack of
a data type. It is used to tell the program that no data type is specified or needed.
Wow, okay so that is a lot of information that doesn't mean a whole lot out of
context. Let's take a look at a few variables now, and you will get a better sense
of what they are, and how they are used.
It would be better if you can follow along on your Arduino IDE at home, open
up:
File → Examples → 02.Digital → Button
Okay so in this block of code let's point out the variables, the comments can give
you a hint. Here they are:
const int buttonPin = 2;
const int ledPin = 13;
int buttonState = 0;
Now you might be asking about the const before int since we didn't talk about
that yet. Const is an abbreviation to tell the compiler that the next variable is in
fact fixed and should not change. While it isn't strictly necessary for the
program to work, it stops potentially damaging things from happening, like
accidentally switching an input pin for an output pin or any number of other
ways in which changing important data could harm your program. For things
that will not change, but still, need to be identified and referred to, const tells the
compiler, ‘Whoa if someone’s trying to mess with this number once it's declared,
don't do it and give an error message instead!’ We will be talking about
declaring variables next.
So, in this example, you can see three variables, and they have been given
names. The first is called buttonPin , the second is ledPin , and the last one is
buttonState . Now to refer back to the values that were assigned to these
variables, the coder can instead put the variable name, and it will give the same
value when it is checked for its contents. You might also wonder, ‘Wow, do
programmers not understand capitalization?’ What's up with the weird way the
name is spelled? Well, that comes down to what is called ‘naming conventions’
for variables in programming.
There is a whole discussion to be had about different ways to name your
variables and methods and classes in programming. The reason for this is to try
and improve readability for the other people trying to read your code. So what
are the conventions for variables?
Variables should start with a lower case letter, and be in camel-case, or, the first
letter of every word in the variable capitalized. No underscores needed, e.g.,
buttonState.
Though, there is one exception for ‘constants.’
Constants should be entirely in uppercase and words should be separated by
underscores, e.g., BUTTON_PIN, LED_PIN.
Okay, so we just talked about constants in our example, and we can see already
our example code doesn't follow our naming conventions for constants. What
does this mean?
What it means is that they are just that, conventions and not hard set rules one
must follow for the program to work. Okay so why even bother with it in the
first place? So far, the coding examples we have given have been short, and
simple. But, in a large sketch for say controlling the motion of a robot, for
example, there will be all kinds of things going on. There will be variables,
constants, calculations, you name it, and it will be happening. These tricks, like
using upper case letters for constants, are ways to make sure that your sketch
does what you intend for it to do.
All of this comes back to best practices. You can write a program and name
your variable ‘rainbowsprinkles,’ but that variable name is not going to mean
anything when you revisit that code later on. Small things like capitalization go
a long, long way to drawing your attention to the right places. This is the same
reason why the Arduino IDE color codes keywords, to help your eye visually
catch on to that cue.
Having said that, there are a few rules you do have to follow. The variable name
must start with a letter, not a number, cannot contain any symbols other than an
underscore, and must not be an Arduino keyword that is reserved for specific
functions, such as ‘ Void.’
Before using a variable, it must first be ‘declared.’ What this means is that it
needs to be named, given a data type, and it should be initialized before being
used. This last part is not strictly required for the program to compile, but, once
again, for coding best practices, you really should get in the habit of doing this.
Undeclared variables have the potential to cause all kinds of weird and strange
things to happen if you use them incorrectly because the data could be almost
anything. It will just point the computer to look at a specific block of memory,
and that value will be whatever was written there last. When you declare a
variable by initializing it, you can be sure it is in a known state and makes
troubleshooting bugs much, much easier.
As mentioned before, if you use a variable in a program it must be declared.
What does this mean? Let's make an arbitrary example variable to track the pin
of an LED since we will be using that in our next chapter as an example. A pin
is just a whole number so integer data type will be appropriate, and the name can
just be what its job is. Let's have a look:
int ledPin;
Believe it or not, that's all it takes to declare a variable. Although nothing has
been assigned to ledPin just yet, we can use it in our program now and start
assigning information to it now that it is declared. Let's initialize the variable
now by giving it a pin number, let's choose pin 9.
ledPin = 9;
Now we have told the compiler ledPin should be given a numerical value of 9.
The next time we use ledPin in a function or equation, the compiler will know it
has this value in turn. It is, in fact, possible to declare a variable and initialize it
at the same time, and this is by far the most common way you will see variables
declared. To do that you just combine the two statements together like this:
int ledPin = 9;
Now anytime we call ledPin we will get the value of nine until we modify that
variable. This is a clean and elegant way that most coders will declare variables.

Constants
In Arduino, there are certain preset variables known as ‘constants’ for use in
your sketches that have certain useful values. Let's look at them now:
INPUT / OUTPUT / INPUT_PULLUP
HIGH / LOW
TRUE / FALSE
LED_BUILTIN

INPUT_PULLUP tells the AtMega Micro-controller that you would like to use
the internal pull-up resistors connected to internal power. This is useful for
things such as buttons to get a clean signal. To activate this feature, you only
need to specify INPUT_PULLUP as the pin direction for functions that accept
input or output.
LED_BUILTIN we will discuss in some detail in the next chapter, but it is
essentially an onboard LED that you can access without having to know the
specific pin associated with it.

Digital Input/Output Functions


There are three Digital I/O functions that allow us to control digital data to the
pins of our AtMega micro-controller. They are:
pinMode(pin, mode) // mode is INPUT or OUTPUT
digitalWrite(pin, value) // value is HIGH or LOW
digitalRead(pin) // reads if pin is HIGH or LOW input

Analog Input/Output Functions


Thre are also three Analog I/O functions that allow us to control our analog data
pin on the AtMega micro-controller. They are:
analogReference(type)
// Configure reference voltage for analog input:
DEFAULT, INTERNAL, INTERNAL1V1,
INTERNAL2v56, EXTERNAL
analogRead(pin)
// Reads value at pin, maps value between 0 and 1023
analogWrite(pin, value)
// Writes analog value (pulse width modulation) to pin. Duty cycle
between 0 always off) and 255 (always on)
For a complete list of functions, and variables you can find them by following
this path in your Arduino IDE:
Help → Reference
If all of this seems dry and tedious, just hold on, we almost ready to break down
our very first sketch together line by line. It is the ‘hello world’ of
microprocessors — the LED ‘blink’ circuit.
Chapter 2

Our First Program

Alright, to get started on our first program we will have a look at the built-in
example first, and then modify it to make our own version. Let’s first take a
look at the built-in example line by line to fully comprehend what every element
is doing. To follow along open:
File → Examples → 01.Basics → Blink
Okay, let's go through this code starting after the comment block. First, we call
the void setup() function which only runs once. Within it, we see pinMode
(LED_BUILTIN, OUTPUT); a function that's called during setup. What does
this line do? We already know from the comment that it initializes digital pin
LED_BUILTIN as an output. What does that mean? LED_BUILTIN is a
keyword in Arduino. It actually has a different value depending on which
Arduino product you choose. On the UNO this is pin 13, but in all cases, it
corresponds to the built-in LED that is on your physical Arduino board.
OUTPUT is another, more obvious keyword. Its purpose is to tell the chip you
want things to travel outwards from that pin. Instead of memorizing if it should
be 1 or 0 for output or input, they have assigned keywords to the direction you
want to use the pin to makes sure you have it correctly set.
Okay what about pinMode(); what does it do? This is a function that takes 2
arguments or parameters. When it is called, it will set the pins on the Arduino
chip according to the arguments or parameters you passed onto it. The first
parameter is the pin number in question. LED_BUILTIN , as you recall, is
usually equal to 13, we could have just as easily typed in 13, or put 13 into
another variable to do the same thing, but by using LED_BUILTIN, the code is
usable on multiple different pieces of hardware without having to worry about
what the correct pin should be. The second parameter is the direction, input or
output. We supplied the value output so this will set the pin to output current
from the specified pin.
We have already touched on void loop() this is the main body of the program,
and everything contained between the braces { } will continue to run until the
power is turned off. Next line:
digitalWrite(LED_BUILTIN, HIGH);
Again, the comments help to determine what is happening here. To tell the chip,
we want to change the state of the pin from ‘off’ to ‘on,’ we need to use a
function that accesses those tools from the chip. DigitalWrite() is the code we
can use to indicate just that. Like pin mode, this function also accepts two
arguments, a pin number, and high or low. We supplied LED_BUILTIN and
HIGH , and now the compiler knows to toggle the default led pin to high or on.
The next line is quite self-explanatory, delay(1000); delay simply tells the chip
to wait the number of milliseconds supplied in the argument. In our case, 1000
milliseconds or one second. The way the computer accomplishes this is fairly
technical, but essentially the chip works on an oscillator that provides a certain
number of vibrations per second and using this information the chip can count
the number of oscillations needed to reach the time value supplied within delay.
Again pretty darn technical, all you need to take away is that delay will count for
the milliseconds supplied in the argument.
The last two lines I'm sure you can figure out now that we have gone over other
examples. In digitalWrite (LED_BUILTIN, LOW); we are turning the light back
off again. And then, just delaying for another 1000 milliseconds or one second.
Put all these lines in a loop together, and you see it does just what it says on the
tin. Light comes on for 1 second, light goes off for 1 second, repeat. Next, let's
write our own similar program that instead makes the LED light on pin 9 blink.
You'll see the code is nearly identical, and in fact, this is how it should be. A
code is basically a tool that you are writing so it will do something for you.
When you go from hammering a big nail to a small nail, you don't need to create
a new hammer, you just change the nail. In programs when you need to do the
same task again and again, you should be able to reuse old code and just modify
the names and values to suit your new needs. This is how programmers save
time and effort by recycling old code they created for some other task and
repurposing it for the new task.
Yet another reason why having clear, concise comments is critical to your long-
term programming success. Your beautiful comments will help you find that key
piece of coding you've already created in a snap, and plug it into the new sketch
you're working on. This is how the pros do it. Let's see how we can get this
sketch to work with an LED on pin 9:
// the setup function runs once when you press reset or power the board
void setup() {
// initialize digital pin 9 as an output.
int ledPin = 9;
pinMode(ledPin, OUTPUT);
}
// the loop function runs over and over again forever
void loop() {
digitalWrite(ledPin, HIGH); // turn the LED on (HIGH is the voltage
level)
delay(1000); // wait for a second
digitalWrite(ledPin, LOW); // turn the LED off by making the voltage
LOW
delay(1000); // wait for a second
}
That's it! If you noticed all we did was declared a variable for an led on pin 9
with the line int ledPin = 9; and then just replaced all the instances of
LED_BUILTIN with ledPin , the new variable we just created. It's that simple to
reuse existing code once you know what you're doing!
Chapter 3

Logic Statements

Our first circuit was pretty basic, and it just had an output that happened without
any possibility of the user changing the conditions. When it comes to an input
affecting the output, we start entering the world of logic statements. Logic
statements are effective ways for you to check the value of a variable, against
some over value. That other value can be a known quantity or a variable
quantity. Using logic statements is how you gain control of what happens next
in your sketches. Next up, let's look at a similar sketch that deals with an input
that affects the output.
To follow along in Arduino IDE the path is:
File → Examples → 02.Digital → Button
Notice how similar this code looks to the last one? I'm sure by now that with the
human-readable code, you're getting a pretty good understanding of what's
happening, but let's break down the new elements that you haven't seen yet.
In the first part of the program, we are initializing constants and variables which
we have already touched on. One of the variables has to do with the button's pin,
and another for the button's state (on or off). In setup, we see that we are again
using pinMode to initialize the pins, but this time our button pin has the direction
of INPUT, to tell the chip this will have current going ‘in’ as opposed to going
‘out.’
Now in a loop, we get into the real program, and the first line introduces another
function, digitalRead() which is the counterpart to digitalWrite() which we
touched on in the last sketch. This function, however, only has one parameter, a
pin number to read from.
Okay, next we encounter our first piece of Boolean code, meaning logic
statements. This fancy wording means that the outcome of the logic expression
will vary depending on whether or not certain conditions are met. The comment
already tells us our condition perfectly. Check if the button state is pressed.
When pressed it should show HIGH. The expression is an ‘if’ statement, and
that piece of code will only execute the code within its curly braces when the
condition in the brackets is true. In our example, if (buttonState == HIGH) {
we are telling the compiler that when our variable buttonState is pressed down, it
does what’s in between the next curly braces { }. The double equals sign means,
‘Is equal to the value of it.’ When you use two equals in a row, you are asking
the compiler to check if a variable has a certain value recorded there. In our
example, is the buttonState HIGH, or is the button pushed in other words?
When this condition is true the now familiar digitalWrite() function is used to
turn the LED on.
Next, we see an ‘else’ statement with its own curly braces. Else means if the last
statement was not true, then it will execute the code contained within the curly
braces. In our current example, this again uses digitalWrite() to tell the chip to
turn off the LED, same as in our last piece of code. Note that while this sketch
has an else statement, it's not required for an if statement to provide an else
statement. Instead, if the condition isn't met, it will not run that code and it will
go past it to proceed to the next instruction.
And that's it! That's all that's needed to make an LED blink at the push of a
button. Alright, we've gotten some pretty simple circuits out of the way. Next,
we will move on to a more advanced idea, ‘while’ statements.
To follow along, open up:
File → Examples → 05.Control → WhileStatementConditional
The first part of this sketch will look quite familiar to you. We are declaring the
variables we will need, initializing them, and setting the pins to the correct
settings which are either input or output. Once we hit the main loop of the
program, we see our very first while statement. Let's take a look at it now:
while (digitalRead(buttonPin) == HIGH) {
calibrate();
This statement is fairly complex so let's break it down piece by piece. First,
while statements do mean something within the curly braces, as long as my
condition is true. So what is our condition first of all? If the button is being
pressed. You will remember from our last lesson that digitalRead will return the
value of a pin, high or low. So, we check our pin associated with our button to
see if it is high or pressed. If that is true, it will run calibrate (); a function that
the user will define later. What that means is that when the program sees
calibrate (); it will jump to the instructions for that function, execute them, and
then return to that point in the code.
Let's look at that function now since it is being called:
void calibrate() {
Right, so this might look pretty familiar to you. It’s extremely similar to our
setup () and loop () functions that we are already using. What this line of code is
telling the compiler is that you want to define a function with the name calibrate,
it will return ‘void,’ and it takes no ‘arguments.’ What does all that lingo mean
exactly? First, defining calibrate means that if we type that word into the code
elsewhere, the compiler will search for a function by the same name and then
run it's code like we are doing now. What about returning void what's that
business?
We haven't really touched on this yet, and we just took the for loop for granted,
and setup has the word ‘void’ in front of it. This function does also work, but
that's not always the case. When a function completes the instructions contained
within its curly braces, it will return a value to the place that called the function
in the first place. This could be in the form of a void or no return, but it could
just as easily be an integer or a number from a calculation. Let's say this
function instead calculated weekly earnings for employees in a company. It
could very well return a ‘float’ (floating point number/decimal number) that
contained the value of those earnings to be used elsewhere in the program. What
would that function look like? Here is a made-up example of a possible function
to do just that.
float weeklyPay (name, hours, rate) {}
Okay so it will return a float, where does that number go and how do we get at
its data? That has to do with calling the function. Let's take a look at that now.
employeeEarnings = weeklyPay (employeeName, hoursWorked,
payRate)
Here is how we would call our arbitrary example for an employee's pay. Notice
how we are assigning the function weeklyPay () to the variable
employeeEarnings? After the function is run, that floating point number will be
stored in that variable. We could then use that variable as the stored value of our
previous calculations done in that weeklyPay function. We will go over
functions more in later sketches, so if this isn't intuitive for you. Don't worry, we
will see more examples coming up.
Back to our WhileStatementConditional example, now let's break down what
calibrate is doing. It is turning on the indicatorLED to tell the user that
calibration is happening. Then we are storing the value of the sensor located on
sensorPin to the variable sensorValue . Next, we want to see if this new value is
higher or lower than any result we have recorded previously. We do that with if
statements. Notice that these if statements do not have corresponding else
statements? Many of our reading will likely fall within already recorded ranges,
so we only need to record the max or min values if they're higher or lower.
Those statements are simply checking if that condition is true. Once all of that is
complete, the function calibrate returns void, or no value is returned.
Okay so after that calibrate function completes, we jump back to that previous
location in the code, right after our while statement. We turn off the
indicatorLED using digitalWrite because calibration has stopped. Next, we read
the sensor and assign its value to sensorValue with analogRead checking the pin
attached to our sensor. Now, this next line introduces a new function we haven't
seen before. What would you do if you didn't know where to find out what this
function does?
In Arduino IDE open up: Help → Reference
A web page will open up with all of the keywords, Boolean logic symbols,
functions, and important information that Arduino uses for you at a quick,
convenient place. Using this resource find ‘map’ and click on it. Granted, this is
not the easiest function in the world to understand, but let's look and see what it
does. The description says it maps a number from one range to another. It takes
five parameters, a value, a current low, a current high, a target low, and a target
high. With this information, it will scale value to a different value in between
the target range by using math to fit it within our ideal scale.
Practically, what does this do? In our sensor, we don't know what values it will
return, nor do we really know what range our data set will fall in. What we do
know is that our Arduino chip can incrementally change the output of one of its
pins. That increment range is one bit or 0-255 as a number range. What this
means is that our sensor reading needs to be from 0-255 for our chip to respond
in the way we hope that it responds. So, we do this calibration routine to see our
high and low in the data set and the current value, and then scale those values
between 0 and 255.
Now the map function says it will not change values outside of the specified
range as this could have intentional uses. For this, you must also use the
‘constraint’ function before or after to put constraints on what the possible values
should be. Let's look at a constraint function for our next line of code. This one
is much easier to understand. It accepts a value, a minimum, and a maximum.
The value will be left alone if it falls within the range, or set to either min or max
if it is outside of that range depending on which it is closest to. Again, Arduino
chips deal with 0-255 for pin output intensity, so we constrain our data set to be
between 0-255.
The last line of code in the sketch fades the LED with the calibrated value after
we just made sure that the data will be within the pin's accepted range of values.
There is also a special kind of while statement we should touch on, it's nearly
identical, but can be very useful in some cases:
do {
// Some code to execute goes between the curly braces
}
while ( conditional statement);
The difference here is that this statement doesn't check for its condition until
after the ‘do’ block has already run. These ‘do while’ statements are for when
you want a while statement, but you need the code inside to run at least one time.
Chapter 4

For Loops

‘For’ loops are unique kinds of conditional statements in that they will continue
to do something for as long as its condition is true. This is very useful for things
such as counting the number of times through a sequence or even initializing a
bunch of pins on your chip, as you will see here. Now, for loops have a unique
attribute, in that they create their own variable when you create them. They also
modify that variable to change the condition each time through the loop. Let's
look at an empty for loop for a moment.
for (variable; condition; increment/decrement) {}
The variable is usually an integer, and you should name it for what it is doing. If
it is going through the pins on your chip, ‘thisPin’ is a very good name, because
it makes sense what it is for. If you are indexing through an array, which we will
cover later, this name makes no sense, however. In that case, the variable name
index might be appropriate. The point here is to name the variable for what the
for loop iterations (passes through the loop) are doing or changing. Next, the
conditional statement. This takes the form of a Boolean comparison. By
Boolean, we mean >, <, >=, <=, ==. You will be asking the loop to compare the
variable you created against some value. In our example, it is 8.
Finally, we come to the increment or decrements part of the for loop. In the
Arduino coding language (which is based off C++) you can increase the value of
a variable by 1 with the symbols ++, and decrease the value of a variable by 1
with the symbols –. Let's see that now in a separate case.
int pizzaSlices = 1// We only have one slice of pizza
pizzaSlices-- // we ate a slice, and now pizzaSlices will be 0
pizzaSlices++ // our friend gave us their slice, now we have 1
Hopefully, that will clarify how increments and decrements work. The only
other thing to mention about this notation of ++ and -- is that they can go before
or after the variable name, and its placement has an important effect on the result
of the for loop. If the symbol is before the variable name, e.g. ++thisPin , it will
change the variable before executing the code in the curly braces. When the
symbols go after the variable, e.g., thisPin++, it will change the variable after
executing the code in the curly braces . This is important to know so you can
make sure you run your loop the intended number of times. Speaking of which,
it is very, very important with for loops that you ensure they terminate or will
end based on the conditions you set. Otherwise, your program will just hang
there, and run the same lines of code until it's power is turned off.
For example, if you wrote a for loop like this:
for (int index = 2, index > 1, index ++) {
The condition in this for loop will remain true forever, and thus it will never
terminate. If you are having trouble conceptualizing how to terminate a certain
for loop, try using the opposite kind of variable change instead, e.g., changing an
increment to decrement or vice versa. Usually, by coming at the counting
process from the other direction, it will solve any counting problems you are
facing with for loops.
Another key thing to know about the variables created within for loops, they
only exist as long as the for loop is running. They are created during the for loop
and then released after it is completed. Why does this matter? Normally you
cannot have two variables of the same name. But here you see us initializing
‘thisPin’ three times in this code, one for each separate for loop. That's because
those names still make sense, but they don't exist after each loop finishes running
To follow along open up:
File → Examples → 05.Control → ForLoopIteration
At the beginning of this sketch, we initialize a variable for a timer, something
we've seen plenty by now. Then we get to set up, and we see our very first for
loop.
We declare an integer variable ‘thisPin,’ that we will use during our conditional
statements. We check to see if it's condition is still true, and then after finishing
a pass, it will increment ‘thisPin’ by one.
Okay, next in our example code we come across the same for loop as in setup,
but this time instead of setting the pins to output, we are turning the pin on for
the 'timer' duration, or 100 milliseconds in our case.
Here we reach a different for loop, so let's take a closer look at it now:
for (int thisPin = 7; thisPin >= 2; thisPin--) {
Again, our variable is ‘thisPin’, and it is initialized to seven. Our condition this
time is while ‘thisPin’ is less than or equal to two. Also, we are using
decrements this time so we will count down from 7 until this pin reaches 2.
Now when you run this circuit, the LED's turn on in reverse sequence because
we are running our ‘for’ loop in the other direction. Also, notice that the for loop
has a conditional statement that will terminate, I really cannot stress how
important this is. The remainder is the same code we have seen earlier to turn
the LED on for ‘timer’ duration.
Next, let's talk about arrays and see how they can also relate to for loops.
Chapter 5

Arrays

Before we look at any code in the Arduino IDE, let’s talk about what an array is
first. Let's say we had a group of things say names, that we wanted to keep track
of. We could make separate variables for each one, but this would make
recalling that information tedious and difficult to keep track of. There is a better
way, and that is through an array. Let's look at an empty array first:
datatype variableName[] = {}
Here, this data type can be any of our variable types like int , float , name , etc.,
that you've seen already. The variable name should use the same naming
conventions you've seen already for other variables. Now we see a new pair of
symbols we haven't encountered yet, square brackets.
Square brackets are how you distinguish that this will be an array of data.
Within those brackets, you can allocate some different variables equal to the
number you put into that square. That means you can have that many separate
chunks of information.
Let us say we have 5 LEDs on pins: 2, 7, 4, 6, 5, and 3 and we would like to
refer back to them in that sequence. We can write that as an array.
name ledPins[5] = {2, 7, 4, 6, 5};
Here, we have told the compiler to set aside 5 name variables, and we initialized
the array by providing those names right away. So how do we access pin 2 in
the array? I'll tell you a hint, it has to do with the number between the square
brackets, but before you can answer that you need to know a little something
about the way Arduino indexes arrays. Arduino uses what’s known as ‘zero
indexing,’ which means when you are accessing elements (data) of an array you
always start at zero. So because of this, we would access pin 2 like this:
ledPins[0]
As counter-intuitive as this may seem, there are some useful reasons in
programming to use zero indexing. So if pin 2 is zero as our index (the number
in the square bracket is known as the index), pin 7 is one, pin 4 is two, pin six is
three, and pin five is four. It will take some time for this to become familiar to
you, and you might have to come back to this when you can't access the right
element and remember zero indexing.
So as an example of using the data within an array something basic would be:
digitalWrite(ledPins[0], HIGH); // Turn on Pin 2
We can also declare an array without putting data inside it right away and instead
decide to initialize it later. Let’s use our same example and see one way that
could be done:
int ledPins[6];
ledPins[0] = 2;
ledPins[1] = 7;
ledPins[2] = 4;
ledPins[3] = 6;
ledPins[4] = 5;
ledPins[5] = 6;
It is also possible to declare an index without specifying the index size and
instead simply filling the data set. However, when doing the array declaration
this way you must initialize the array right away:
int ledPins[] = {2, 7, 4, 6, 5, 3};
The compiler can count the number of elements for us and allocate the space
needed to hold our variables, and it can be accessed by index exactly the same as
before, starting at 0 for the first element, all the way to n-1 for the final element.
Next, let's look at an array in an actual sketch to see how they are useful to have
in a practical example
To follow along open:
File → Examples → 05.Control → Arrays
At the start of this code, we see a timer variable and the same array we just
looked at a moment ago. In this example, this array is the pins our LEDs are
attached to. Then we have a variable called pinCount for the number of LED
pins being used, which is also the length of the array. You will see why this
variable is used in a moment.
Let's move on to setup(). We have a ‘for’ loop that will initialize the pins. We
create a counter variable for the pins we want to access same as before thisPin
and initialize it to zero. Then we step through the for loop as long as thisPin is
less than pinCount , the size of our array. Then we increment to end our ‘for’
loop once it reaches six, the value of pinCount .
Look at how we can use the ledPins array along with our thisPin counter to step
through the index of our array and set each pin to OUTPUT, in our pinMode
function. Arrays and ‘for’ Loops work fantastic together, and you will see them
working together very often in coding.
In fact, you will see it twice more in this same sketch. In a loop, we use another
for loop with our ledPin array to turn the LED's on for ‘timer’ duration in the
sequence as it's read left to right: 2, 7, 4, 6, 5, 3. Then in the second block of
code, we will turn the pins on in reverse sequence using a decrement counter
instead, turning the pins on right to left: 3, 5, 6, 4, 7, 2. You can do a lot more
than just turn LEDs on and off with arrays and for loops, but this is a great visual
example of sending 'power' through multiple pins in a sequence.
Chapter 6

Logical Switches

This chapter we will be talking about switches. They are very similar to a series
of if statements, in that they 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 basic switch now.
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 7

User Defined Functions

One of the ways you can help keep your code neat, organized, and modular
(reusable) is to use functions in your code. Additionally, they help make your
code smaller by making certain sections reusable. Functions are like tools that
were created to serve a particular function, as the name suggests.
While we have already encountered a few user-defined functions, we will cover
them in greater detail now and explain some of the features we may have glossed
over when we encountered them last time. Let's look at the declaration of a
function now:
float employeeEarnings (float hoursWorked, float payRate) {
float result; // this will be the value we return when this
function is called. It should match the datatype before our function
name
result = hoursWorked * payRate
return result // return tells the function to send a
value back once to where it
was called
}
This function clearly takes two arguments, hoursWorked , and payRate , both of
which are ‘floats.’ It does some simple math on them and then returns a float as
a value. Return means to terminate the function and send back whatever value is
placed after the word return, usually a variable, as the result of some
calculations.
Let's see us call this function now to get an employee's earnings:
void loop () {
float hoursWorked = 37.5;
float payRate = 18.50;
float result = employeeEarnings (hoursWorked, payRate)
// result will be 693.75
There are a few rules to follow with functions, however. First, the function must
be declared outside of any other functions. This means you need to write the
code for the function you are creating outside of either setup() or loop() , or any
other user-defined function.
Let's see another example that sample sketch that could be used to smooth sensor
readings:
int sensorSmoothing (analogPin) {
int sensorValue = 0;
for (int index = 0; index < 5, index++)
digitalWrite(LED_BUILTIN, HIGH); //Turn on LED for
smoothing
sensorValue = sensorValue + analogRead(analogPin)
delay(100) // 100 millisecond delay between
samples
}
digitalWrite(LED_BUILTIN, LOW); //turn off LED
sensorValue = sensorValue / 5 // average the
values over five samples
return sensorValue;
}
This kind of function can be used for smoothing the data input of many sensors
if they are prone to jittery inputs. This will average the samples to give a more
consistent flow of data. You can see that this code is very similar to our last
example:
void loop () {
int sensorPin = 0; // analog pin 0
int sensorValue = sensorSmoothing (sensorPin);
}
Here, when we try to initialize our sensorValue variable it will call the
sensorSmoothing() function on analog pin 0, and return the average result over 5
samples)
Functions do not always need to have parameters or return variables either.
Sometimes functions can return no value and have no parameters. All they do is
execute a few lines of code and then terminate bringing the compiler back to
place in the code they were called. Let's see a function like that now:
void calibrate() {
// turn on the indicator LED to indicate that calibration is happening:
digitalWrite(indicatorLedPin, HIGH);
// read the sensor:
sensorValue = analogRead(sensorPin);

// record the maximum sensor value


if (sensorValue > sensorMax) {
sensorMax = sensorValue;
}
// record the minimum sensor value
if (sensorValue < sensorMin) {
sensorMin = sensorValue;
}
}
We saw this code back in our while statements section, but it has value, so we’re
going to touch on it again here. Notice how this function returns no value and
accepts no value. It is just a clean, elegant way to perform a function in your
code. If you need to calibrate the code several times, this function can save you
many lines of code (and time), and it also makes it look much easier to read.
Both these things are positive, and this is why you will certainly come across
many functions in the sketches you see from other people in the community.
That covers a basic overview of user-defined functions and should give you a
foundation on how to start creating your own toolkit to use in your own
sketches.
The next chapter will be a summary of some general coding best practices that
you should keep in mind to improve your sketches!
Chapter 8

Best Practices

Contained in this chapter will be some of the best practices you can adapt to take
your coding to a higher standard. We have touched on this first topic already,
but we will expand and reiterate here. First up is naming conventions.

Comments
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.

Coding Best Practices


Follow naming conventions
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


User-defined functions are a great way to accomplish this. By doing this,
you can write a segment of code in just one place and refer to it each time it
is necessary. This makes better sense and is much cleaner and simpler to
read.

Write a flow-chart of your sketch before you start coding


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


E.g., if it is a function named ‘flickerLeds’ (pinValue ), it better be flickering
some LEDs!

Avoid pointers
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. This is a great
way to meet friends and learn so many new ways to do things you may not
have thought about previously.
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


E.g. stepMotor(), getValue(), smoothReadings() , etc. All these names
explain with an action word what this function should be doing.

Make the name describe the purpose of the 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.
Conclusion
Thank you for making it through to the end of, Arduino: The Ultimate Beginner's
Guide to Learn and Understand Arduino Programming Effectively , let’s hope it
was informative and that it was able to provide you with all of the tools you need
to achieve your programming goals whatever they may be.
The next step is to get out there and start making your own sketches! Go to your
local hobby store to get some ideas, or go to the community to see what new
projects you might want to try. After you have an idea where you might want to
go next, (robots are pretty fun!) join the community! Seriously, it's a lot of fun
to build projects with friends and compare them with each other. It's also a
fantastic way to learn and grow as a hobbyist.
You can also check out some more advanced concepts we didn't have a chance to
touch on here such as headers, classes, changing the clock speed for the chip,
adding cores, adding libraries, there is so much that you can do with this chip, it
really is incredible. Pick a direction that interests you and see where it takes
you. I hope that this guide has offered you some small inspiration to go out there
and try new things and see what your sketch designing skills are capable of.
Finally, if you found this book useful in any way, a review on Amazon is always
appreciated!
C++
The Ultimate Beginner’s Guide
to Learn and Understand C++
Programming Effectively
Introduction
Congratulations on purchasing this book and thank you for doing so. The
following chapters will discuss everything that you need to know to get started
with learning the C++ programming language. This is a great language to learn
because it allows you to work on almost any kind of program or application that
you want and it is really easy to learn how to use it. This guidebook will go over
all the things that you need to know to get started with using the C++ language
for your own needs.
There are so many great topics that you can explore when it comes to working
with the C++ language. This guidebook will explore what C++ is all about, how
to get it all started, how to work with your own syntax and create the first code
that you might want to use, how to work with variables, loops, and arrays, and
even the importance of conditional statements and operators inside your code.
Once you are done with this guidebook, you will be ready to write some of your
own codes!
There is so much to learn about the C++ language. It is a great option that will
help you get ahead, and knowledge of how this programming language is used
will help make sure that you can get any task or program taken care of. Once
you are ready to get started with the C++ language, make sure to read through
this guidebook to help you out.
There are plenty of books on this subject on the market, so thanks again for
choosing this one! Every effort was made to ensure it is full of as much useful
information as possible, please enjoy!
Chapter 1

What Is C++?

When it comes to finding a programming language that has a lot of history


behind it, you can’t go wrong with C++. In fact, this is one of the first languages
in the world that was used and it can help you learn how to code. Because it has
been around for so long, there is a large following, and serious programmers and
coders will make sure that they know at least the basics when it comes to the
C++ language.
As you can guess, C++ is a programming language that will help you write some
of the codes and applications that you may wish to design. Like many of the
popular coding languages that are available today, C++ is considered an object-
oriented programming language, or an OOP. This means that this coding
language revolves solely around objects, rather than actions. This makes it easier
to write out the codes that you want and can prevent some of the major issues
that often come up when you use other programming languages.
C++ is a great coding language to learn because it was designed to have a lot of
flexibility and function. It is also very quick, which makes this a great
programming language to work with on many projects. There are actually many
ways that you can use the C++ language, and they include the following:
Prepackaged scripts
These are really important to you as a beginner because they will help you
practice some of the hacking techniques that we will talk about in this
guidebook. These are packaged ahead of time so that you can learn without
having to set it all up on your own.
Video games
C++ is the language that is behind the creation of many popular video games that
are out right now. While this guidebook won’t go in depth so much that you can
create your own video game once you are done, it is definitely something that
you can learn how to do with understanding this programming language.
Web pages
There are many web pages that rely on the C++ programming language because
this language is really easy to manipulate and you can use to quickly and easily
make any kind of website. You can even use this language to help you come up
with some cool interactive features. Popular websites like eBay and Amazon
utilize this kind of programming language.
Phone apps
If you are a fan of using your smartphone and playing with some of the apps that
are available, you may find that working with C++ can make it even better. This
programming language can help you to create your own smartphone apps in no
time.

The history of C++


C++ is a programming language that is rich in history, as it is literally the
beginning of programming languages. It started before computer programming
was even much of a thing. Before people started hacking for a living. It started
back around the time of telephone hacking back in the year 1979. That is how far
back the history of this language goes. There are not really any other
programming languages that go this far.
Bjarne Stroustrup was working on his thesis for his doctorate, and he decided to
work with a programming language that was known as Simula. This language is
one of the first programming languages of the computer age. However, it was
very slow and full of bugs.
Strousup came up with the idea of ‘C with Classes.’ A programming language
that was a lot faster than Simula. ‘C with Classes’ later became ‘Cfront’ which
sped up the process of creating a programming language. However, Cfront was
left in the dust when C++ came along, because it added compilers into the
language, making it a lot easier, and faster to use than any other programming
language available at the time.
Since then there have been annotated reference guides and updates to the
language to make it better and faster, and even easier to use. C++ for Dummies
is a popular guide for this programming language.
C++ is one of the most popular programming languages out there today. This
language is used by plenty of industries for their systems, and so rather than
make a new language which takes a lot of time, they just adapt C++ to many
different things because it is the most versatile.
Why do programmers use this language?
There are a lot of different programming languages that are available, and you
may be curious as to why some programmers would rather go with C++ rather
than some of the other options. First, many programmers like that C++ has a lot
of speed and flexibility. This is an older language, but it is more than capable of
keeping up, and it can provide you with a program or an app that you will be
proud of. The C++ programming language is also great for beginners to try
because once you learn the basics of how it works, you will find that it can help
you with the basics of other coding languages.
In addition, if you would like to learn how to use a coding language that is good
for other things outside of just coding on computers, then C++ is the one that
you need to learn. While it does wonders with the codes that you want to write
for websites or on your computer, it does well with fulfilling other functions as
well.
Those are just a few of the reasons why people love working with the C++
language so much. Some of the other benefits that you will surely fall in love
with as you start learning how to use this programming language include:
A big library
Since C++ has been around for a long time, they have a very extensive library.
This is available for you to use so you can pick out the codes that you want
inside of your script and save some time and even learn some new things. You
can also create some of your own codes if you wish, but this library is really
helpful for the beginner who is still learning, and it can definitely help make
writing a code easier.
Ability to work with other languages
C++ is a great language to use along with some of the other programming
languages out there. This makes it easier to really work on the projects that you
want because you can add in the parts that you like from different coding
languages and combine them together to create results that are really amazing.
Works on many projects
Most other programming languages can only focus on just one or two little
projects. For example, using JavaScript means that you are just going to be
working on websites. But with C++, you can use it to help with a lot of different
projects. Whether you want to work on a website, planning to create a new
program, or do something else with programming, you can do all of these with
the help of C++.
Fast and reliable
If you have used some of the other coding languages that were popular in the
past, you will find that sometimes they aren’t the most reliable. Information may
slip through, or they won’t start working the way that you would like. If you
want something that works the first time and is reliable, then it is a good idea to
go with C++.
Offers a lot of power
Those who like to work in programming and want to have a lot of power in
creating their project will find that C++ is the right option for them to choose. It
offers a lot more power than all of the other programming languages you can
find out there.
These are just a few of the benefits that you can enjoy once you learn how to use
the C++ programming language. It may seem a bit more difficult to use than
some of the others, such as Python, but it has a lot of the power that you need,
and it can also work well with other programming languages. With a bit of
practice, you will get all the basics of this programming language down and
really enjoy this programming language by doing so many things you haven’t
even thought of before.
Chapter 2

How to Work on Your First Program

Now that we know a little bit about the C++ program, it is time to get started
with our own code writing. This is an exciting activity, and you probably have a
lot of ideas on what kind of code you want to write out, but let’s start with some
of the basics. The first thing that you need to get started on writing your own
code is an ‘environment.’ The environment is the place where you can write out
the code and get it to execute various tasks for you which is why this is an
important part to focus on. The good news is that there is a lot of these
environments available online for you to pick from and many of them are free
depending on which features you would like to go with.
Once you have downloaded the C++ environment that you would like to use, we
are going to start right in with your first code. This is a simple ‘Try this’ code
that will only take up a few lines but will have some very basic parts of the
syntax already present inside to make things easier to learn. The code that you
would have to use to make this work includes the following:
#include <iostream>
using namespace std;
int main ()
{
court << “Use This One!”;
return 0;
}
You have a few options available when it comes to writing this out. You can
choose to write this out in your compiler, which will be available in your
environment, or you can choose to write it out and save it to your computer. The
second option is sometimes nice because then you have the code saved and
could copy and paste it any time that you would need it in your code.
Either way, you should carefully consider the type of text editor that you want to
work with. Most of them are going to be device specific, so you need to look for
the one that goes well with your particular computer. Some of the options that
you can go with are Windows Notepad, vlm , vl , Brief, and EMACS. If you
would like to have an editor that is compatible with more than one platform, then
the vlm and vl options are the best ones to choose.
When you write out your own codes, you should write them out in the text editor
first to get a rough draft on the program and then you can move them over to
your compiler later on. This makes it easier for you to check your work and
avoid mistakes with the code that you are currently working with.

C++ compilers
Just like with the text editors, there are many compilers out there that you can
work with. The problem is that while you do get a lot of choices to pick from,
many of these compilers are pretty expensive. That is because most of the
compilers that you will come across are meant for elite hackers who have
mastered what was in the other lower level compilers, and now they want to
make sure they can take it to the next level.
The good news is that there are some compilers that you can get for free. You
just need to be careful and watch out, just make sure that you are getting ones
that are good and will have all the features that you are looking for. One
compiler that works out well with C++ and can be good for a beginner to use is
GNU . It is best when used with the Linux systems, and you may already have
this one on your system. To check whether the GNU compiler is available on
your system, use the following code:
$ g++ -v
If the compiler is installed, then you should see this message on the screen:
Using built-in specs.
Target: i386-redhat-linux
Configured with: ../configure –prefix=/usr …...
Thread model: posix
gcc version 4.1.2 20080704 (Red Hat 4.1.2-46)
If you typed in the code above and you did not get that message to come up on
the screen, it means that you either did not download the compiler properly or
you do not have it on your computer in the first place.
Basic syntax
The C++ language can be defined as a program that will use objects to help keep
everything organized and will allow the code to communicate and complete
other functions using various methods. There are four important parts that come
with the C++ language and these include:
Classes
These are the organizational tools for your language. They can be seen as boxes
that can hold onto or store objects and will sort out similar ones. You can label
your class anything that you would like, but it is good coding practice to place
objects that, in one way or another, have similar characteristics into the same
class.
Object
Objects are things in your code that have states and behaviors. These could be
things such as colors, texture, shapes, and so on. You will usually classify these
objects into classes that have similar objects. So, if you had a class that was
about dogs, you may put the different types of dogs in that same class.
Method
This is a term used in coding for behavior. There can be as many or as few
methods as you would like to work with. This is how you can manipulate the
data and actions will be played out based on the method that you are working
with or using. Without using the right method, your program won’t know exactly
what it’s supposed to do.
Instant variable
These refer to the individual objects that you are working with. Each one is
classified using a unique set of variables that act like the fingerprints to identify
your object. You can use some values to assign the right variable to the object
when you create it.
And that is the basics of writing a code in C++. You should take some time to
write out the code above in your compiler to gain a little bit of practice to
understand what it is that you should be doing here. We will have a look at some
of the things that you can do with these codes later on, but this is a great place to
start.
Chapter 3

The Syntax of C++

We spent some time looking at an example of a code in the previous chapter and
some of the things that you will most likely find in your code. Now that this is
done, it is time to go a bit more into the syntax of how you are supposed to write
your own code. The syntax is so important because it helps ensure that your code
is written in a way that the compiler will understand. Let’s break down a few
more parts of a basic C++ code so you can learn how to write the programs that
you want.

Program comments
The first thing that we are going to have a look at is the comments. These are
nice when you want to leave a little note inside of the code you are writing.
These comments help others who look at the code understand what you are
trying to do with the code. As a beginner, you will probably find a lot of codes
that will include these comments as they were put there so that you know what is
going on with that code.
These comments can help guide you so you can accomplish the task you want to
complete using the code and you add in as many of these comments to your code
as needed, though you should try to keep them to a minimum, so it doesn’t mess
with the code too much. When the (//) symbol is used, it tells the code that you
are writing out a comment. The program will not read over these so it will not
disrupt your code at all. Just add in those symbols in front of your code and then
proceed with the rest of your code as soon as you are ready.
You can also write a comment that is a little bit longer when you are using the
C++ language, something that other coding languages will not. When you want
to have a double or multiple line code, you will use the /* to start the comment
and the */ to end the comment. When your compiler sees these, it will stop
reading until the second part shows up. At that point, it will start reading through
the code again.

Data types
You can also work with a variety of data points as well. You will often work with
what are known as ‘variables,’ which are just reserved spots in your memory
which make sure that the parts of the code are completely safe. There are a
variety of data points that you can use, and they include:
Boolean
Character
Integer
Floating point
Double floating point
Wide character
Valueless

Why is it so important to start new lines in C++?


When it comes to writing out the code that you want to create and use, it is
important that you use just the right amount of line spacing. It is not a good idea
to write out the whole code in one long line, though you can technically do this
and the code will work just fine. The compiler will not notice whether the code
is in one long line or you have it separated out into different lines. However, it is
much easier to read the code in C++ or another language, if you separate out the
lines instead of writing it all out.
Consider this:
{
cout << Try This;>> endl; << Today I ate Pizza and did
Math;>> endl; <<6=(7-1);>> endl; << That is what I learned
today;>> endl;
return 0
}
This line is technically right. You can put it into the compiler, and it will still
read through all of this just fine. However, it is really hard to read through this,
especially if you are still a beginner to the concept of coding. This particular one
would not be that bad, but if you get to writing a longer code, it would be almost
impossible to figure out what is going on or to even catch mistakes that you may
have made.
There is another way that you can write out the code. It will mean the exact same
thing and the compiler will read it the same way, but it is better because other
programmers, as well as yourself, will have a little difficulty trying to read
through the code. A better way to write out the code is this:
{
cout << Try This;>> endl;
<<Today I ate Pizza and did Math;>> endl;
<<6=(7-1);>> endl;
<< That is what I learned today;>> endl;
return 0
}
As you can see, this is much easier to read through. It says the exact same thing
as the first one, but it looks a lot better, and it’s easier to read, thus, easier to
understand. Good coding practices will require you to write a code like the
second example, rather than the first one, although both will be accepted just
fine by your compiler.

Functions in C++
Working with functions is another thing that you will often have to do in writing
your code. A function is basically a group of statements that can work together
to perform a task. Each program that you create in C++ has a minimum of one
function, which known simply as the main ‘(),’ and usually, you need to add in
more than one of these functions so your code will work exactly the way that
you want it to be.
You can take over in several ways. First, you can choose to divide up the code
into several functions based on what you want to do. How you decide to divide
up your code amount these several functions is up to you, but most programmers
will go with the logical choice and divide up each function so that it performs its
own task.
A function declaration is a component that tells the compiler about a function’s
name, parameters, and the ‘return’ type. A function definition, on the other hand,
is what will provide the actual body of the function.
The C++ standard library will provide numerous built-in functions that your
program can call. For example, the function strcat() can be used to concatenate
two strings and then you can use the memcpy() to copy one memory location to
another location. These are just a few of the functions that you are can work with
and they all work similarly.
So, let’s take a look at how the functions in C++ will work. You can define it
with the following:
Return_type function_name (parameter list ) {
Body of the function
}
These function definitions will consist of a function header and a function body.
The parts of the function are composed of the following:
Return type
The function that you are working on may return a value, and you will use the
value of return_type to get something to return here. Some functions will be able
to do the operations that you want without returning a value to you. With the
syntax that we used above, you would end up with ‘void’ as your answer.
Function name
This is the name that you will give to the function. When you add in the name of
the function with the parameter, you will get what is called the ‘function
signature.’
Parameters
The parameter is a placeholder. When you invoke the function, you are passing a
value over to the parameter. This value is often referred to as the ‘actual
parameter’ or as the ‘argument.’ The parameter list will then be able to refer to
the number, order, and the type of parameters of the function. It is possible to
work on a function that does not have any parameters at all.
Function body
And finally, the function body is what contains the collection of statements that
can define exactly what the function does.

Modifier Types
When you are working on a code using the C++ language, you will find that
double , int , and char will be allowed to have a modifier that comes ahead of
them. The modifier is used to alter the meaning of that base type so that it can
help fix any issues that you may deal with when you’re trying to create a
program. The following are just a few of the different types of data modifiers
that you can work with:
Short
Long
Unsigned
Signed

These four modifiers can be applied to any of the integer base types. You can
take ‘signed’ and ‘unsigned’ and use it on the char , and then ‘long’ can only be
used on ‘double.’
C++ will also allow you to use a shorthand notation for declaring the ‘long,’
‘short,’ and ‘unsigned’ integers. This means that you can use those words
without having to add in the word int because this is already implied.
There are also different types of qualifiers you can use so you can make sure
your C++ code will work. The kinds of qualifiers that you can use to provide
some additional information about certain variables are the following:
Const
Objects that have the const qualifier cannot be changed by the program while
you are executing it.
Volatile
The ‘volatile’ qualifier will tell the compiler that you can change the value, but
these changes may not be explicitly specified by the program.
Restrict
A pointer that has been qualified by 'restrict' is initially the only means by which
an object it points to can be accessed.

Exception handling
Another thing that you can work with in trying to write your code is exception
handling. An exception is a problem that can arise when you decide to execute a
program. A C++ exception is what will happen in response to an exceptional
circumstance that usually occurs while the program is running. The most
common type of exception that can be raised is when the user tries to divide by
zero.
Exceptions can be useful to have in your code because they will provide you
with a way to transfer control away from one part of the program and then move
it to another part. The C++ exception handling is built upon three main
keywords, and they are ‘throw,’ ‘catch,’ and ‘try.’ Let’s take a look at how these
will work inside of C++:
Throw
The first one that you can work with is the ‘throw’ keyword. What it will do is
that it can make the program throw out an exception when a problem shows up.
This can be done simply by using the throw keyword.
Catch
A program can ‘catch’ on to an exception with an exception handler at a place in
a program where you would like it to handle the problem. If you use the catch
keyword, it will tell the program that you want to catch that certain exception.
Try
When you use the ‘try’ keyword, it will identify a block of code where particular
exceptions can be activated. When you go with this one, it is usually followed by
at least one catch block.
Assuming that your block will raise up the exception, a method can catch an
exception using a combination of the try and the catch keywords. These will then
be placed around the code that may end up with that exception. It does not
automatically mean that the exception will always happen, but there is a
possibility that it can happen.
Chapter 4

Variables and More in C++

One important aspect of working with C++ is working with variables. These are
really significant as they ensure that all the aspects of your code will match
together and that the program can bring them up whenever they are needed.
When you use these variables inside of your code, you are basically saving a
spot on the storage of the computer. This helps you to bring them up when the
code executes. All of the variables that you will work with can be attached to
different types, and then these types will determine the layout and the size of the
memory that goes for that variable. It will also set up a range of values that you
can store on that specific spot of the memory.
You will find that naming the variable is similar to naming your identifier. You
can choose to use numbers, letters, and even an underscore to name the variable.
You can’t start with a number when you make a name as it must start with a
letter and all the letters that you’ll use have to be case sensitive. Other than that,
you can name the variable anything that you want.
There are a lot of variable types that you can go with. Some of the most popular
variables are:
Wchart _t
This is known as the variable for wide character types.
Double
This is a floating value that has double precision.
Void
This is the variable that shows up to represent that there isn’t a type being used.
Int
This is an integer.
Float
This is the floating point, and it can only have single precision.
Bool
This is a variable that returns results which are either true or false.
Char
This is the representation of one byte in the memory and is a type of integer.
You also have the power to define other types of variables. These variables can
include options such as classes, data structures, enumeration, reference, array,
and line pointer.

Defining the variables


Now it is time to move on to defining the variable. These definitions will tell the
compiler how much storage it’s supposed to use and where you would like to
store and create the variable. It can also help you specify the data type that you
want to use. You can type it out as: ‘type variable_list.’ You can choose just
about any of the variable types that we talked about above and then write them
out in the same way. These will tell the compiler to create the variable type that
you are listing so that the code will work how you want it to. Let’s take a look at
an example of how this will go below:
#include <iostream>
using namespace std;
int. main ()
int j=10;
int k=5;
int l=j+k
{
cout <<l>> endl;
return 0
}
You should get the answer 15
You can also go through and define as well as declare the variables that are in
your program, but that is something that we can work on after getting a little bit
more practice with this language. It is a good idea to bring up the compiler and
try out the code above. This can help you to get more familiar with writing codes
and can help you to start recognizing when you will see these variables.
You will often need to assign some kind of value to the variable that you are
working with. On its own, the variable is just reserving some space on the
memory of the computer for the work that you are doing. It is your job to go
through and add in a value to make this happen. The value of a specific variable
is stored right where you stored the variable.
You can also go in and store more than one value for each variable. You can
technically store as many values as you would like to a single variable as long as
you go through it the right way. However, it is best to keep the variable to value
ratio down to one or two to make sure that the code doesn't get too confusing and
that the code works the way it should.
To assign a value to your variable, all you have to do is use the equal sign. This
will automatically tell the compiler that the variable (or the space that you saved
on the memory of your computer) belongs with that specific value. When that
variable is called up while your program is executing, it will bring up that value
for you.
Working with variables is not all that difficult, but it is so important to make sure
that your code works properly and that the values you want to use in the code
will show up at the right times when your code executes.
Chapter 5

Arrays and Loops

Now it is time to get a little deeper into some of the other things that you can do
when it comes to working on code in C++. You can do some amazing things
when you start to bring in arrays and loops to the mix, and this chapter will
spend some time focusing on how you can get both of these components to
work. You will be amazed at how much you can accomplish in your code with
just these two powerful options. So, let’s just go right in and learn how to use
arrays and loops in writing your code.

Arrays
Let's get started with arrays. Arrays are a type of data structure inside of C++
that is capable of storing elements that are basically the same type and the same
fixed size. These are a collection of the same type of variables. But instead of
going through and using individual variables to do this, you can work with one
array or an array of numbers. To do this, you can use the numbers 0 to 99 and
then each one can be accessed by the index of the array.
These are similar to variables in the sense that they are a location in the memory,
but they are more continuous than what you can find with a variable. The lowest
being the first element while your highest element will need to be the last. You
have a few options when it comes to working with arrays. You can choose to
initialize them one by one, or you can do this with a sing statement. A good
example of doing this is the following:
double balance [5]= {1000.0, 2.0, 3.4, 17.0, 50.0};
The numbers that are found in the bracket that we wrote should never end up
higher than the number of elements that you plan to use. This means that if you
place a five in the brackets, like we did above, and then place six numbers into
the array because there will not be enough space in the memory to do this.
However, it is possible to not specify the size of the array. This is helpful if you
are not sure how big the array will be ahead of time so that you can add in as
many numbers as are needed. You would write it out like this:
double balance [] {1000.0, 2.0, 3.4, 17.0, 50.0};
This example will give you the same array that you got in the previous example,
but you started out by not specifying the size of the array. This got the program
and the code to do it for you.
Now that we have taken some time to look at how an array can be written, it is
time to learn how you can personally use this information to make the array
work inside of your program. This program is sometimes seen as a bit more
advanced compared to what we were able to do before, and the example that we
will go through will add in a few more elements, but this is a great way to really
help you to learn how these arrays are supposed to work and it will help make
sure that you will see your code work out the way that you want it to. A good
example that you can use in your code is this:
#include <iostream>
using namespace std;
#include <iomanip>
using std::setw;
int main ()
{
int n[ 10 ]; //n is an array of ten integers
// initialize elements of array n to 0
for ( int i=0; I <10; i++)
{
n[i] =i+100; // set ekement at location I to i+ 100
}
cout << element << setw(13) << value<< endl:
//output each array element's value
for (int j=0; j<10; j++)
{
cout << setw(7)<< j << setw(13) <<n[j] << endl;
}
return 0
}
Before we proceed, take some time to open up your compiler and write out this
code. This is a good example that shows an array works and will give you some
practice to understand how arrays are supposed to work. This program will be
able to use the array to use the setw() function so that you can format the output
that you will get. This is just one example of how you can work with arrays and
get them to come with the best results for you.

Working with loops


Now it is time to move on to understand how loops will work inside of your
code with C++. These loops are meant to save you some time when you are
writing out your code. If you need to have the code repeat a single part a few
times or a bunch of times, you do not want to waste so much time writing it out
each repetition manually. This will take up a lot of your time and can really
make the code look convoluted and hard to read through.
With a loop, you can take the part of the code that you want to repeat, and you
only have to write it once. But it is set up in a way that the code will repeat itself
over and over again until your conditions are met. It is important that you set up
some conditions inside of your loops. If you forget, the code might reach a point
where it could get stuck or frozen because it does not know when it is supposed
to stop. But if you do this the right way, you will find that a loop statement can
help you to get a lot of work done, and it will make sure that your code looks
nice and at the same time, complete most of your tasks.
There are different kinds of loops that you can work within the C++ language,
and we will take the time to look them over each one carefully.

‘While’ loop
The first kind of loop that we will have a look at is the ‘while’ loop. The while
loop will keep going through the loop and will repeat it as long as certain
conditions are met. The program will go through and test for that condition each
time it goes through the loop and will restart the loop cycle each time that the
condition is met. Once the conditions are no longer true, the loop will stop, and it
will continue on to another part of the code.
The syntax that you can use to implement the while loop happen in your code is
this:
While(condition)
{
Statement(s):
}

‘For’ loop
The second type of loop that you can work with is known as the ‘for’ loop. This
is the kind of loop that will only repeat if the conditions are true. With the while
loop, it will go through the loop at least once and then check to see if the
conditions are true. With the for loop, the program will check to see if the
conditions are true before it runs through the loop. This means that depending on
the input that it is getting, it is possible that the for loop will not repeat inside the
program at all. If you want to make sure that the loop executes at least once, then
you will have to go with the while loop. If it doesn't really matter how the code
works, then you would be fine with the for loop.
If you have decided that your program can do well with the for loop, then you
want to write out the following code to make it happen in your program:
For (iit: conditions: increment)
{
Statement(s);
}
Do… while loop
Another option that you can choose to go with is the 'do…while loop.' This is a
loop that is similar to the while statement, but it will wait to check on the
condition when you reach the end of your statement, rather than doing it at the
beginning. This is how you will write out this kind of loop:
Do
{
Statement(s):
}while (condition):

Nested loops
The third loop that you can choose to work with when it comes to using loops
that you want to write in your code is the nested loops. This is when you will
have a loop that is inside of another loop. Both loops will continue to run at the
same time until both of their conditions are met and only then will they end. This
kind of loop allows you to create a continuous loop of loops. This may be
confusing, but the syntax is pretty easy to work with, and as you progress
through with using C++ and expand your knowledge, you may find that you will
use the nested loop a lot more often than you would have thought. To write out a
nested loop using the C++ programming language, follow this example:
while (condition)
{
while (condition)
{
statement(s)
}
statement(s) // you can put more statements
}
At this point, you may be curious as to why all of this is important to your
coding. Right now, you’re probably asking yourself: “Why do I have to work
with arrays and with loops to write my own code?” These seem kind of
complicated, and you may feel like you only want to work with some of the
basics to make a good code for beginners, rather than going into stuff that is far
more advanced.
The time will come when you have to decide that you want to branch out and
expand your knowledge on some of the topics that you’re already familiar with
when it comes to this programming language. You may like completing the
simplest tasks while you’re still starting out, but you won’t be able to take full
advantage of writing codes if you don’t go beyond what you already know. This
will make the whole process of coding pretty boring, and if you really want to
make some really useful programs and impress the people around you, you must
be willing to take it all to the next level to see some great results.
Even though arrays and loops may be considered a little more advanced than
what you have worked with in the past, it is still something that will help you
create much more sophisticated codes and can help prepare you for some of the
more complicated stuff.
And the next step is important, as you want to progress, and you want to become
better. You want to move on to the next level so that you can feel a sense of
achievement in the fact that you succeeded past the beginner level, and this will
help put those nagging thoughts of doubt to rest.
There are so many things that you can do if you learn how to create and execute
loop statements and arrays. Loop statements are most often used in video games
and robots. Things that need to function without the creator being there to
manually assist with the function by typing in each individual code. You have to
wind it up, and just let it go.
Arrays are used to create web pages, like shopping websites, for example,
because you can add a list of variables with ease, and never have to really do
much of anything past the initial setup. You will find that at some point in the
future, you might want to work on your own website. Whether you are making
websites from scratch for a client or if you are interested in writing your own
website for personal use only, there is nothing better than being able to use
arrays to create one of your own. Even if you choose to use a premade website,
knowing how to use arrays and read some of the codes that we have discussed in
this guidebook will make it easier to understand the code and perhaps make
some of your own changes in the code of the program if needed.
There are also a lot of times when you will have to work with putting loops in
your coding. These loops really do make things easier when you are working on
a code, as you don’t have to write out as many things inside the code because it’s
all right there for you, often in just a line or two of coding.
Think of it this way, what if you would like to get the computer to write out a
program that lists all the numbers from one to twenty? Or what if you would like
to get the code to make out a multiplication table that goes all the way from 1x1
to 10x10? With some of the things that we talked about before this chapter, you
can imagine that this would take up an awful lot of time and coding to do if you
were not using loops.
Do you really feel like writing out the code that many times? Do you want to end
up rewriting the same part of the code ten, twenty, or one hundred times? This is
a waste of valuable effort, and it will just make the text of your code look like a
horrible mess. This is why using the loops are so important. Depending on what
kind of task you want to get done and the kind of loop that you need to use to
accomplish it, it is possible to get all those lines of code done with just a few
simple lines of code to initiate looping.
If you plan to use some loops in your code, it is a good idea to take a look at the
different kinds that are available and pick out the one which is best suited for
your needs. Each of them is great and will help get the job done, but the way that
they get the job done will depend on the loop that you’ll work with. Learning
how each of them works will ensure that your code behaves properly when you
are ready to execute them.
While these may be a little bit harder to work with, you will find that arrays and
loops can add a ton to the code that you are working on. Make sure to give them
a try and experiment with them a little bit so you can see the results that you
want in the programs and applications that you are planning to write.
Chapter 6

The Importance of Operators in C++

Now it is time to talk about the operators that are used in C++. These operators
are pretty basic to work with, but they can add a ton of power to the code that
you are working on, whether we are talking about C++ or some other coding
language. With any coding language that you decide to learn about, it is
important that you spend some time and learn how to use these operators. These
operators are in charge of telling the program what you want it to get done and
can give all of your codes have a little bit more power.
There are four main types of operators that you can work with inside the
program, and each of them can help make sure that the program will behave
exactly as you programmed it to. You will quickly see how each of these will
work and it won’t take you long to figure out how you would use each one in
whatever code that you’re planning to make. The four main types of operators
that we will focus on with C++ are:

Relationship operators
Arithmetic operators
Assignment operators
Logical operators
Let’s spend a little bit of time with each type of operator so you can understand
how each one is supposed to work and when you should use them in writing
your own code.

Logical operators
The first of the operators that we will have a look at are the logical operators.
These logical operators will help you to compare the different parts of the code
that you are adding to the system, and it can also help you understand whether
they are true or false, if they go together, and more. Some of the common logical
operators that you can work with are:
(!)
This operator is known as the logical ‘not.’ This can be used any time that you
want to reverse the status of your operand. So, if you have a condition that is
false, you can use this operator to make the condition true.

(&&)
This operator is known as the logical ‘and.’ This can be used if you have two
operands that do not equal zero. If this happens, then the condition will end up
becoming true.

(||)
This operator is known as the logical ‘or.’ When you are working with this one,
the condition will be true if at least one of the operands ends up being equal to
zero.

Arithmetic operators
The arithmetic operators are probably the easiest ones to work with, and they are
likely the ones that you will use inside of your own code the most. If you have
ever done any math before, and you probably have like most people do, then you
should easily recognize most of the operators that you will see under this
category. These arithmetic operators will allow you to divide, multiply, subtract,
and add together your conditions or your statements based on what you want the
program to do. Some of the most popular arithmetic operators that you may want
to use in your code are the following:
(+)
This is the addition operator that will add together two operands of your choices.
(-)
This is the subtraction operator. It takes the right-hand operand and subtracts it
from the left-hand operand.
(*)
This is the operator that makes it possible to do multiplication in the C++
language.
(/)
This operator helps you to do division in C++.
(++)
This is the increment operator. It will increase the value of your operand by one.
(--)
This is the decrement operator. It will decrease the operand value just by one.

Assignment operators
The third operator that you may have to work within your code is the
‘assignment’ operator. This one is pretty common to use as well and it will not
take you too long to start recognizing some of these operators in the codes that
you might use and write. This assignment operator is responsible for making it
easier for you to assign a name to your variable and you can then use these
operators to save, search, and do so much more inside the code you are working
on. Some of the most common assignment operators that you can work with
inside the code are:
(=)
This operator is the simple assignment operator. It assigns the value of the
operand on the right hand to the one that is on the left.
(+)
This one is called the ‘Add and’ operator. It adds together the values of both
operands and then assigns the sum of these over to the operand on the left side.
(*=)
This is the ‘Multiply and’ operator. It multiplies both of the operands and then
gives the results over to the operand on the left side.
(-=)
This is the operator that subtracts the value of your operand on the right side
from the one on the left and then gives this difference to the left operand.
(/=)
This is the divide and operator. It divides the value that is on the left side from
the one on the right side and then assigns this amount to the left side.
It is important to note that these assignment operators are just the most common
ones that you can work with. There are some other assignment operators that you
may come across as you are writing codes inside of C++, but those are reserved
for more complicated codes and should not be something that you have to focus
on right now. For the most part, the codes that you will write just use the (=) as
the assignment operator so that you can assign the right value to the variable that
you are using, but there are times when the other assignment operators will come
into play as well.
There are a few different options that are available when it comes to the
arithmetic operators. First, you can use more than one of these operators at a
time. So you can add together a few different numbers or add some and divide
others if you would like. If you decide to use more than one type of arithmetic
operators, remember that you will need to work with the order of operation to
ensure you get the right answers.

Relational operators
And the final type of operator that we will talk about is the relational operators.
These operators have different ways of helping you to get your code to work the
proper way. Some of the relational operators that you can work with to make
your own code are:
(==)
This is the operator that will check the equality of your two operands. If they are
equal, then the conditions are considered true.
(>)
This operator will check the value of your operands. If the operand on the left
side is higher than the one on the right, then the condition is considered true.
(<)
This operator is basically the opposite of the one above. If you find that the value
of your operand on the left side is greater than the one on the right side, the
condition is considered true.
(!=)
This one checks the equality of your two operands, and if the values are unequal,
your condition is considered true.
(<=)
This operator checks whether or not the operand on the left side is less than or
equal to the operand on the right side. If it meets these criteria, the condition is
considered true.
(>=)
This one will check if the value of the operand on the left side is greater or equal
to the one on the right side. If it is true, the condition is considered true.
As you can see, there are a lot of different operators that you can work with and
use. Each of them can help you do a lot of different things inside the code and,
they can make your code even more useful as these components will help add
more functionalities so the code will also be efficient. They may look like simple
additions to your code, but these supposedly simple additions can make all the
difference.
Chapter 7

Decision Control in C++

The next topic that we are going to discuss is how to work with the conditional
statements or the ‘decision control’ statements. There are times when you are
working on a program, and you want to make sure that it is capable of making
some decisions for you even when you’re not there. This could happen when you
would like the user or another programmer to put in some information, and then
you want the program to respond based on the conditions that you set.
You can get the program to act a certain way based on the conditions that you
add to the code. The decision making capability is a great way to ensure that the
program does what you would like it to do even though it is a bit more
complicated, there is a ton of times when you might want to add this to your
code so learning it at this point can be a great idea.
There are a few different types of decision control statements that you can work
with. For example, you can choose to go with one that only allows you to get
one answer and call it right. There are conditional statements that will give out
an answer based on the various answers that the user will put in. Or you could
end up with one that gives out a list, like a menu of items and you can let the
user pick from there. Let’s get into this chapter and take a look at the different
types of conditional statements that you can work with and use.

Switch statements
The first type of conditional statements that you can work with is the switch
statements. These statements can help you out a lot because they will allow you
to check out whether your variable has an equal value against the other values or
the other cases that you outlined in your code. The variable that you would be
checking in here would be compared against a variety of cases by the statement.
A good example of the syntax that you can use to create one of these switch
statements is this:
Switch(expression){
case constant-expression:
statement(s);
break; //optional
case constant-expression:
statement(s);
break; //optional
//you can add in as many of these case statements as you would like
Default: //Optional
statement(s);
}
When you are working with the switch statements, there are some rules that you
have to follow to make them work inside of your code. First, the expression that
you use with the switch statement should be either an enumerated or an integral
class type. In addition to this, it can also belong to a class that has a conversion
function. The good news is that when you are working with C++, there isn’t a
limit to how many of these case statements that you can add into this syntax so
you can either make it long or short depending on what your code wants. The
important thing to remember here is that you need to add in a colon as a value to
each one that you want to use as well.
Once the variable finds a value that it is equal to, it will just keep on running
until it finds a way to break the statement that you wrote. When the system
finally finds this break statement, the switch will stop whatever it is that it’s
currently doing. Then, the control flow is going to pass on to the next part of the
code. You do not need to add in a break statement to the cases. If you do not
have one of these break statements, your control flow will just pass on to the
next part automatically.

The ‘if’ statements


The next type of conditional statements that you can work with is known as the
‘if’ statement. One of the most basic things that you can create when it comes to
conditional statements, is the if statement. These are based on a true or false
statement. If the system decides that the input matches up to the conditions that
you set, it is true, and the program is going to run the part that you added to it.
For example, if you set it up so that the system asks what 2 + 2 is and the user
puts in the right answer of 4, then this would be seen as true and the message
that you pick, something like ‘That is correct!’ will show up on the screen.
Any time that you have the user input some kind of information and if the
information they added meets up or complies with your conditions, then it will
proceed to show up the statement or other things that you add into the code. But
what is going to happen if the user puts in the wrong answer? If the user puts in
that 5 is the answer to the question, ‘What is 2 + 2?’ then it will fail to meet the
conditions that you set and the program will see this as false.
Since the if statement is one of the most basic forms of the conditional
statements, you will find that it is not capable of handling a false answer all that
well. If the user puts in any number that is not 4 as the answer for the question
that we had placed, then the if statement will see this as false, it will leave the
screen as blank, and nothing else will happen. This could be a problem for a lot
of the codes that you want to write, and this is why you won’t always find
yourself working with the if statements.

The ‘if’ else statements


As we discussed in the past part, using the if statement will leave you running
into some limitations along the way. You will have various issues you’ll have to
fix if the user ends up putting in the wrong answer and the program sees this as a
false statement based on the conditions that set in the code. This is where the ‘if
else’ statement comes into play.
The if-else statement can be put to work in a variety of situations. Not only does
it allow for the user to put in an answer that may not meet your conditions, but
there are also times when you may want it to let the user pick from a few
different options to start with. The if-else statement can help you to do all of this
and the syntax for this is pretty simple. To create an if else statement, copy this
example of the syntax:
if(boolean_expresion)
{
//statement(s) will execute if the boolean expression is true
}
Else
{
// statement(s) will execute if the boolean expression is false
You can then add in as many of these points into the if else statement as you
would like. If you want to work on creating your own program that is capable of
setting apart various people into five or six different age groups, is a task you
can accomplish with the help of these if-else statements. You just need to add in
some more of the ‘else’ keywords to make this happen.
So, let's take a look at how all of this will work and keep it really simple. Let's
say that you are making a program that requires a user to solve the equation, 2 +
2. If the person guesses the right answer and inputs 4, you will be can set it up so
that the first part is the true statement and then the message that you created to
inform the user was right will come up on the screen. But, if your user puts in
the wrong answer, or anything other than 4, then the program will assess that the
answer is false based on the conditions that you set. Instead of going blank
though, it is possible for you to add another option and get another statement,
such as ‘Sorry, that is incorrect’ to come up on the screen.
As you can see, this gives you a lot of freedom when it comes to the things that
you can have your program do. You can keep it as simple just like the example
that we did above, or you can add in some various other things to make it more
sophisticated and to also ensure that it’s compatible so it can work with the code
you’re writing.
Another thing that you want to keep in mind when it comes to working with
these if statements, is that you can add in some more of these if-else statements
if needed and it is even possible to add in some of these if else statements inside
of each other. This makes it pretty complex for someone who is just getting
started, but with a bit of practice and patience to learn how to use the syntax, you
will find that it will add a ton of power and flexibility to this process and will
make it so much easier to do some of the various tasks that you would like your
code to accomplish.
Working with the if statements and the if else statements can make your coding
experience so much better. It allows the system to make decisions based on what
the user is putting into the system rather than having to be there yourself always
and doing it manually every time. Make sure to try out a few of these different
types of statements and see how they work within your code and keep practicing
on using these statements so you can discover the various functions they can
fulfill.
The ‘elif’ statements
Another option that you can work with is the elif statements. These statements
will allow you to take things to the next level. This will allow you to go a little
bit further with your and make your program even better. These elif statements
will list out the options that you would like to be available for your user. Think
about it like a menu in a game. You can list out a few different things on a menu
and let the user pick which one they would like to go with.
This is a great option because you can add a lot of functionality to the code that
you are working on. The user will have the freedom to pick from the different
options that you set out for them, and you can even add in a catch-all to make
sure that you can track if the user does not like any of the results that you are
providing to them.
You can add in as many parts to this as you would like. Sometimes you can only
add in just a few options and other times you can make a long list that will give
the user a lot of choices. You are also able to add in some statements for what the
user will see if they pick each option. The statement that you will add here may
vary based on how you are using the conditional statements inside of your own
code.
For example, let's say that you want to put up a game where you would like to
allow the user to go through and pick out the type of pizza that they would like
to use. You could list out four types of pizza, such as cheese, pepperoni, veggie,
and sausage. The user will pick from those pizzas, and then the corresponding
statement that you set up would execute once the user has made a choice. You
can even set it up so that there is another option for them not to get any pizza and
maybe just choose a drink and that can be the catch-all in case the user does not
want any of the pizza choices that you have listed.
As you can imagine, there are a lot of different options that you can go with
when you’re trying to use the elif statement. You have the freedom to add in as
many or as few of these options as you would like to make your program work.
There are so many ways that you can work with the conditional statements.
These statements are really useful and will help you with making your program
work the way you want it to. You can get it to make decisions for you and even
get it to behave the way that you would like. Make sure to try out a few of these
different options so you can understand exactly how they work and to learn how
they can be used to add more functionalities to the code you’re doing.
Conclusion
Thank you for making it through to the end of this Book, let’s hope it was
informative and that it was able to provide you with all of the tools you need to
achieve your goals whatever they may be.
The next step is to get started with writing some of your own codes in the C++
coding language. This is a great coding language to work with. It is one of the
first coding languages that came out and as soon as you learn how to work with
this one, then the easier it will be to learn some of the other coding languages
that are out there. This is an easy coding language to learn, and it can be used to
help out with your websites, your smartphone applications, and so much more.
This guidebook took the time to explore all the various things that you can do
when it comes to working in C++. We talked about some of the basics that come
with the C++ language, how to design the syntax and your first code with this
programming language, how to work with variables, loops, arrays, and
operators, and how to create your own decision control statements to make the
code work the way that you would like. There are so many different things that
you can do when it comes to the C++ language, and we will have a look at some
of the basics that come with this.
When you are ready to learn a brand new coding language, and you want to pick
out one of the best, make sure to check out this guidebook so you can learn how
to work with the C++ coding language.
Finally, if you found this book useful in any way, a review on Amazon is always
appreciated!
C#

The Ultimate Beginner's Guide


to Learn and Understand C#
Programming Effectively
Introduction
Congratulations on purchasing this eBook and thank you for doing so. The
following chapters will discuss everything that you need to know to get started
with using the C# language. This is a great language to work with as a beginner,
and you’ll be able to pick up on it in no time. This guidebook will provide you
with all the information that you need to get started.
There are so many awesome things that you can learn about and do when it
comes to working on this great programming language, and this guidebook will
try to cover as many of them as possible. We will take a look at some of the
basics that come with the C# language, how to get started with using it, as well
as some of the different types of codes that you can write using the language. We
will take a look at how to work with conditional statements, how to work with
classes and objects, and so much more.
Working with the C# language is a great experience, and you’ll be writing a lot
of great codes in no time. Make sure to take some time to look through this
guidebook to help you get started with writing in this language today!
There are plenty of books on this subject on the market, so thanks again for
choosing this one! Every effort was made to ensure it is full of as much useful
information as possible, please enjoy!
Chapter 1

The Basics of C#

Most people are scared of learning a new coding language. They know that it
would open a lot of doors for what they would be able to do with their
computers, but they worry that coding itself is too hard for them to learn how to
work with. If you do not take the proper time to learn a new programming
language, the whole process of programming could be difficult. But when it
comes to finding a good language that will help you write almost any code that
you would like, then it is time to take a look at the C# programming language.
This chapter will take you through some of the basics that come with using the
C# coding language so that you can start using it yourself.

What is special about C#?


The first thing that you might want to look into when it comes to a coding
language is to understand why C# is so special and why you would even want to
learn how to use this particular programming language. There are many different
coding languages out there to choose from, and they all work differently. Some
people go with a certain coding language because it is easier to use than some of
the others and some will choose their programming language based on the kind
of programming they can do with it.
But you will find that there are a ton of benefits that come with using the C#
program, and we will explore some of them inside this guidebook. Even though
you are just a beginner, this is a great coding language to work with and will
allow you to design so many programs of your own.
While there are many different options available if you want to get started with
coding, none are as great to work with like C#. Some of the benefits of going
with C# rather than some of the other programming languages include:
It can utilize a big library
As a beginner, there are a lot of parts of the code that won’t be easy for you to
learn. You will learn them as you go, but the library that you can use with C# is a
great resource that will be of great help to you. You can place these functions
into the code without a lot of hassle being involved. You can even use them to
make some changes to the code, so it works the way that you want.
Automatically disposes of the functions
When you are working with some of the other programming languages, you will
have to go through and remove the items that you own. This will take up your
time and can be a hassle if you end up missing some of them. Using C# will do
all of this work for you to make things faster and easier.
Easy to learn
C# is widely considered as one of the easiest programming languages you can
learn how to work with. While there are a few parts that are more complicated
than some other coding languages, this is not a difficult one, and you’ll start
recognizing different parts of the code pretty quickly as you continue to use it.
Compatible with Windows computers as well as others
This programming language was originally created to work on Windows
computers and help you design a program for them. But it also works well with
some other operating systems such as Mac, Linux, and more as long as you
download .NET on it. Windows has some great products that are easy to use,
especially for beginners, so you will surely get great results once you get started.
Works with .NET which helps make it easy
This is a program that already comes with the Windows computers, but you can
add it to some of the other systems to make C# accessible on these other
computers as well.
Similar to C and C++
This makes it really easy to work with this program and learn the basics before
going on to these other programs. Even if you choose to stick with this
programming language, you will find that it is powerful enough to do most of
the coding that you want and without all the hassle you might experience with
some of the other programs.

What do I need to get started?


Now it is time to learn what you will need to get started with using this
programming language so you can get to make the codes that you want. The first
thing that you should look at is to check whether or not your code has the .NET
framework in place. You should also have the development kit for this
presentation on your Windows computer. Starting on Windows Vista, this
framework was automatically placed on the computer for you so this will save
you some time if you are working with the right operating system.
If you are on a computer that does not have the .NET framework, you will have
to go with Mono Project rather than working with the .NET framework for your
projects. You can visit the Microsoft store at www.microsoft.com to find the
right framework for the computer that you want to work with.
Remember that this language works the best for Windows computers, but this
doesn’t mean you can’t use it on other systems. If you are working with a MAC
or a Linux computer, you have to make sure that you are working with Mono
Project rather than the .NET framework. You can check out their website:
www.monoproject.com where you can find the right framework for your system.

Getting started with the C# language


After you have gone through and downloaded the things that you need, it is time
to get started with using the C# language. When it comes to working with your
Windows computer, C# is a great programming language to work with. It is
compatible with the .NET framework that should already be found on your
Windows computer. The C# language is also really simple and flexible to use,
and at the same time, it provides you with the power that your codes will need. If
you are someone who is still new to the idea of programming and you like using
Windows products, then the C# language is definitely worth your time to learn
and use.
Just like when you work with Java, C# will not support any code pointers, and
you won’t have any access to working with multiple inheritances. It is important
to remember this because some other programming languages are capable of
doing those things. Rather, memory collection and type checking are what C#
can offer. It also has some powerful and useful features that you may recognize
if you’re familiar with using C++ so you can add a lot of functionality to your
codes. Let's take a look at some of the things that you can do with code writing
in C#.

Writing out a program with C#


The best thing that you can do while you’re still learning how to work with C# is
to actually write out a program and see how the code looks. As an example, we
will write out a simple program that will help you understand what is going on
with C# and how it can be used to help out with other codes that you might want
to write in the future.
The first thing that you have to do is launch the text editor that you prefer using.
If you are using a computer on the Windows operating system, going with the
popular Notepad is a great option. There are also several other options available
depending on the type of computer you are planning on working with. Once the
text editor is open and ready to go, write out the following code inside:
class FirstProgram
{
static void Main()
{
Console.WriteLine(“Using C# is fun.”);
}
}

Now you can access the command prompt and type:


csc FirstProgram.cs
After you issue this command, the compiler for C# will process this file and then
create an .exe file in the same location as your code. For example, if you saved
the original file on the desktop, you should see a new program come up called
‘FirstProgram.ee.’ right in the same place. If there is an error in the code that you
wrote, you will see an error message come up.
Now you can run this application by entering ‘FirstProgram.exe’ into the
command prompt. If everything was done correctly, you should see that the
command prompt will display the message: ‘Using C# is fun’.

Analyzing the program


Now that you have written out the program that you want to use, it is time to
take a look at the different parts of the code and what they all mean. The code
above is pretty simple to work with, and you will find that it will include a
variety of the different components that you need to write out a decent code
inside of C#. Some of the parts that you should look for include the following:
The first line
In the first line, we will include the identifier and the keyword. The keyword is
the word inside the code that has special functions inside the language. With the
keyword that we used in the last example, you were creating a new class for the
program. The identifier is then in charge of listing out the class, the variable, and
the method and the one that we are using here is called ‘FirstProgram’.
The third line
In this line, we will define the method Main(). This is what will act as the
starting point for any of the applications that are on your computer. The program
will always start if the Main() method is executed, no matter where you place it
inside the code. Only two words will fit in there, and one of them will be ‘static’
while the other one is ‘void.’ These will help to determine the kind of object that
is in the code.
The fifth line
This is the final part of the code we are working on. This line is where you write
out the message that you want to come up after the code has been executed. This
method is called WriteLine() and it’s used to make sure that you can write things
out in the code. You can also add any message that you like.
In addition to the things that we talked about above, you may have noticed that
there were braces placed into the code. These braces are there to tell our
computer that there are some blocks of code throughout the program and it will
keep everything separated nicely. Keep in mind that when you write your code in
C#, you have to use a semicolon the same way you do when writing a code with
C and with Java.

Comments in C#
It can be useful to know how to leave comments when you’re writing out a code
with the C# coding language. These comments are helpful no matter what kind
of programming language you prefer to use and can add a little something to the
code that you are trying to create. These are like little notes that will remind you
or tell the other programmers something important about your code. When you
write out the comments properly, the compiler will know that it should skip over
them and will not read through them. You can add in as many of these comments
as you would like, but it is best if they are only used when necessary, so they do
not make the code look too messy.
There are two main types of comments that you can work with inside of C#. The
first one is a ‘single line’ comment. This is written with two forward slashes.
These are used only if you need to write out a small sentence or a few words,
and you want all of it to stay on one line. If you end up using these slashes, and
then you go over that one line, the compiler will notice this and will bring up an
error message.
You can also choose to work with multi-line comments. There are times when
you might want or need to write out a comment that is a little bit longer. You
would not be able to do this with the slashes that we talked about before. If you
would like to write out one of these longer comments, you simply have to write
/* at the beginning of the comment and then end it with */.
It really is that simple to learn how to work with the C# programming language.
It may look a little bit intimidating at first, but with some practice and a
willingness to learn some of the basics that we have already been talking about,
you can start writing your own codes in no time.
Chapter 2

Variables and Types


of the C# Language

When you first get started with the C# language, you will notice that the code is
pretty easy to work with, especially if you have experience working with other
coding languages in the past. While some of the things that you can do with this
programming language are more advanced and a little bit more complicated,
there are plenty of things that are simple and easy to work within C#. We have
already taken a look at one example of a code in C# so let's go ahead and look at
some more of the basics as well so you can do more with it.

Data types
First, we have to take a look at how we’re supposed to work with data types in
C#. A programming language can be divided into two parts, the value types, and
the reference types. When we talk about the value types, what we mean is that
you are the one who’s responsible for passing the data over to whichever method
you would like to use. When you work with the reference type, you will add the
reference in with the method as the value will be placed somewhere else. Some
of the various data types that you can work with inside the C# program include:
Ulong
Double
Long
Float
Uint
Int
Ushort
Sbyte
Short
Byte
Bool

When you use this type, you are only allowed to store two values. The values are
only false and true, so it’s good for making conditional statements and logical
expressions.
Decimal
Char

This is a data type that can only have a single character. When you are writing
the char value, you must include it with single quotes such as writing out ‘t,’ ‘b,’
and so on.

Variables
When you execute your code, the computer program is what will store all the
data for a short time period. Programmers will work with the word variables
when they want to talk about locations of the memory that will hold onto the
data that you created. Thus, the variables will have a value that goes with them,
and that value will be stored where the variable saved the space. When you are
working with the C# language, you can create your own variables with the
following syntax:
<data_type> <name_of_variable>
When you type in the above code to your compiler, you are creating a variable
that will save a part of the memory so that you can store a value there. The
programmer will then be able to access this variable using the identifier it was
given. For example, if you had listed the formula above as char x, you would
have to find the variable by bringing up x.
Using C# will also make it easy for you to initialize the variable during
declaration. This term refers to the process of placing a value to a variable while
you create it. You just have to use the assignment operator. In this case, the
assignment operator will be the equal sign. So, you would do the variable then
add the equal sign and write out the value that you would like to place with it.
After that, the process is done.
You can also declare a few variables in the same statement, as long as you are
using the same data type. You just need to make sure that each of the entries you
are using is separated evenly by a comma.
When you are working with the C# language, you have to declare your variables
before you try to assess them again. C# will also have you implement a new rule
called the ‘definite assignment.’ What this means is that you will have to go
through and initialize the local variables before you can even use it in your code.
This all means that you have to assign the initial value of the local variable while
you are doing the declaration process.
One thing that you need to keep in mind when you are working with C#
language is that the variables are named using this method because the values
that they will store will change each time that you run the program. The values
will change depending on what you place with them.

Creating an identifier
If you look through some of the suggestions that come with Microsoft, you will
find that they will recommend that you use a Camel notation when you are
working with the variables, and it will recommend that you work with the Pascal
notation when you want to work with the methods. Working with the Camel
notation will mean that you will keep the first letter of your name as lower case.
If you are creating an identifier that has a compound word then you will make
sure that the first letter of your second word will start with an uppercase letter:
payment completePayment
mathematics firstClass
The Pascal notation will take things a bit differently. This notation style requires
you to start the first word using an uppercase letter. The first letter in all of the
other words in the sequence should also be written in uppercase as well. Some
examples of using the Pascal notation include:
WriteLine() ReadLine()
Start() Main()
When it comes to naming these identifiers, you can work with numbers and
underscores as well. But, if for some reason you can’t begin the name of these
identifiers with a number, you can write out something like seven books, but you
can’t write out ‘7books.’
Now, these notations are not required, and you can change them around as much
as you would like. But this is considered a proper coding practice if you’re
working with C# so it is best to follow these rules so the code will work exactly
the way that you want it.
As you can see, C# is a pretty easy language to learn. You do not need to worry
about a lot of rules that are too complicated to remember like the other
programming languages, and yet you will still have a lot of the power and the
flexibility to get the most out of coding. The good news about this is that we
have already looked at some of the more complicated parts that come with this
language, so you’re already off to a good start.
Chapter 3

Working with Operators

In this chapter, we will take some time to talk about the operators that you can
work with inside the C# language. These operators are pretty simple to
understand and use but this doesn’t mean they’re useless, in fact, they can help
make sure that your code will perform the tasks that you require it to complete.
Without using some of these operators, your program will lack functionality, and
the program won’t work all that well. These operators may be simple to
understand, but they really add a ton of power to enhance the overall capability
of your code.
Operators are important no matter which type of coding language that you are
working with. We will go into detail on the different operators separately so that
you can understand how each one is supposed to work and how you can work
with each one to fulfill a variety of purposes and accomplish different tasks.

Arithmetic operators
The first type of operator that we will have a look at are called the arithmetic
operators. These operators are pretty basic, and if you have ever worked with
math in the past and you most likely have, you can figure out the functions of
these operators pretty quickly. These operators are in charge or have the purpose
of telling the computer to perform arithmetic functions as required by the user.
As long as you use the right sign and make sure that you put the numbers in the
right order, these arithmetic functions will work out as they’re supposed to.
Some of the most popular arithmetic operators that you can use inside C#
include:
+
This is the addition operator. Its function is to add two operands together. So you
would get x+y=25.
-
This is the subtraction operator. Its function is to subtract the value of the right-
handed operand from the left-hand operand. So you would get y-x=-5.
*
This is the operator that will tell the computer to multiply the two operands. So
you could do x*y=150.
/
This is the operator that will tell the computer to divide the left-hand operand
with the right-hand operand. For example y/x.
%
This is often called the remainder or is commonly known as the ‘modulo’
operator. Its function is to divide the left-hand operand by the right operand and
then returns the remainder.
++
This is the increment operator. Its function is to increase the value of the operand
by one. So you would have ++x=16.

Programmers often call this the ‘decrement operator.’ Its function is to decrease
the value of the operand by one. This means that you will have –x=14.
Working with these assignment operators is meant to be easy. They just help you
to add together numbers or statements or do other similar things with the codes
that you are writing. You just have to make sure that you are using the correct
order of operations when you put your numbers into the code so you can be
certain you’re provided with the right answer after the operation is executed.

Assignment operators
We talked about these a bit in the previous sections when we were looking at
how to assign values to variables in the code. While there are some other options
that you can go with when it comes to working with the assignment operators,
this is the most common way that you will use these operators. In addition, there
are a few different types of assignment operators that you can work with, but the
most common one is the equal sign. Some of the operators that you can to work
with inside of your C# code includes the following:
=
The function of this operator is to allow you to perform simple assignment
operations. It can assign the value to a variable that you are working on at that
time. For example, writing int sample = 100 will tell the program that you want
to assign 100 to the variable that is called ‘sample.’ It won’t perform any
additional tasks on this variable or on the value involved.
+=
This is the additive assignment operator. Its function is to add up the values of
your two operands and then assign the sum to your left-hand operand.
-=
Programmers will often refer to this as the ‘subtractive’ assignment operator. Its
function is to subtract the value of the operand on the right side from the one on
the left side and then assign the difference to the left-hand operand.
*=
The function of this operator is to multiply the values of each operand and then
assign the product to the left-hand operand.
/=
The function of this operator is to divide up the two variables and then take the
result and assign it to the variable on the left.
When you are working with the assignment operators, make sure that you have
both operands that belong to the same type of data. If you find that the various
operands you are using are not compatible, some issues could arise which can
result in an error in the program if you try to execute it and will require
additional time and effort to fix.

Relational operators
The next type of operator that you can use is known as the relational operator.
These operators are very useful because they allow you to compare the values of
two of your operands. Because of this function, these operators are the best to
use when you want to create some conditional statements. We will have a look at
some of the relational operators that you can work with to make your C# code,
but for these examples assume that ‘e = 150’ and that ‘d = 100.’
==
The function of this the operator is to allow you to check the equality of two
values. If the two values end up being equal, the operand will tell you it is true.
Otherwise, the operand will tell you it is false. For example, saying the d == e
would show up as false.
!=
The function of this operator is to allow you to test the inequality of two values.
If the values end up not being equal, it will tell you this is true. For example, e
!= d would result in the operator saying it’s true.
>
The function of this operator is to check whether the operand on the left is
greater than the operand on the right. If it is, then the operator will tell you it is
true. For example, saying that e > d would be true.
<
This is actually less than an operator, it allows you to check whether the operand
on the left side is less than the operand on the right side. If it is, you can get it to
show up as true like the formula d < e .
>=
The function of this operand is that it will say the value of the operand on the left
side is truly greater than or equal to, the operand on the right side. Otherwise, it
will tell you the statement is false. For example, saying that e >=d evaluates as
true.
<=
With this operator, you will get a true if the operand on the left side is less than
or equal to the operand that is on the right side. For example, d <= e is true.
One thing that you should keep in mind when you are working with these
relational operators is that you will get a Boolean result each time. What this
means is that the answer you get will be either true or false. You also have to
check if you are using two equal signs when you are working with the equality
operator. If you end up getting these operators mixed up with your assignment
operator, you will probably get an error message, and that program will not work
out the way that you want.

Logical operators
You can still use logical operators if you are working with the C# programming
language. This is another type of Boolean operator because it will accept a
Boolean value and then give you a new Boolean value once it is all done. This
will rely on a lot of true and false statements if you want to put these into your
code. There are four main types of logical operators that you can work with. We
will have a look at those below but keep in mind that we are assuming that ‘c’ is
true, ‘d’ is also true, while ‘e’ is false:
&&
This operator is called the logical ‘AND.’ It will only result in a true if both
operands are true. For example, d && c will evaluate the statement as true.
||
This is the logical ‘OR.’ This operator will give you a ‘true’ if at least one of
your operands is true. For example, c || e will result in the statement as true.
^
This operator is the logical exclusive ‘OR,’ and it will result in a true if one of
the operands is true. If both operands can be false or true, the operator will tell
you the statement is false.
!
Using this operator, you can reverse the value of your Boolean variable. For
example, if you type in ‘!d’, you will get a false.

Bitwise operators
And finally, we will have a look at the bitwise operators. This is an operator
which will seem pretty similar to what we did with the logical operator. The
difference between the bitwise operator and the logical operator is that the
bitwise one takes in binary values and then create a Boolean result. These
operators will basically work with 0 or 1, and then it will use these as the output.
Let's take a look at how these will work inside the C# language.
For this, let’s assume the following: ‘I = 0,’ ‘h = 1,’ ‘j =0’ and ‘g = 1’
&
This is the operator that is known as the ‘bitwise AND.’ Its function is to assign
1 to the positions where both of the operands have 1. For example, g & h will
give you 1.
|
This is the bitwise OR. Its function is to assign 1 to the positions when there are
at least one of the operands with a 1. For instance, doing h | 1 will give you a
result of 1.
^
This is the exclusive ‘OR’ that will work well for binary data. Just like working
with the logical values, this kind of operator will give you 1 in the areas that the
operand has a 1. For example, if you do g^j, you will get a result of 1.
The bitwise operators are a bit more complicated to understand and use, but for
the most part, there aren’t that many situations where you actually need it. It is
still a good idea to understand how they are supposed to work. You will use them
on occasion, and that experience can come into good use later on with your
coding.
Chapter 4

How to Create Your


Own Conditional Statements

This chapter will take the time to discuss in detail how you can work on your
own conditional statements. There are times when you work on a code, and you
want to set it up in a way so that it can make decisions all on its own. You will
be able to set up the conditions that you want it to follow, but the code will be
able to respond based on the input that the user placed into the computer.
There are a number of different options that you can choose when you are
working with the conditional statements. Each of these will allow you to do
some different things when you are working on your code. But they will add a
lot of power when it comes to the program that you can write and will allow for
some more interaction between the program and your user. Let's take a look at
the different types of conditional statements and how they will work inside your
code.

The ‘if’ statement


The first type of conditional statement that we will take a look at is known as the
‘if’ statement. This is the basic form of this, and while it is more than likely that
you will rely on one of the other conditional statements in your code, it is good
to start with this one to give you an idea of how these conditional statements will
work.
With the if statement, the code is only going to reply if the input of the user
matches up with the condition that you set up in the code. If this happens, then
the code will execute, usually providing the message that you placed into the
code or executing something else that you wanted the code to do. But with this
one, if the user input does not match up with what you set as you condition, then
nothing will happen in the program because you didn’t set it up like that.
This is actually easier to do than it may sound at first. Let’s take a look at an
example of how you would work with the if statement in C# so you can get a
good idea of how they work:
If (x > 0)
{
Console.Write(“The value is positive.”);
}
With the example that we listed above, certain things need to happen. If the
value that the user put sin is higher than zero, then the program is set up to print
off ‘The value is positive.’ However, if the expression turns out to be false, or the
input is less than zero, then the program will ignore the whole statement that
comes after ‘Console.Write’ and it will move on.

The ‘if else’ statement


As you can imagine, there are times when the if statement is not going to be
enough. You do not want to just leave the program this way and have the user
wondering what went on or if they did something right or wrong. You may want
to have some kind of answer come up on the screen regardless of what answer
the user gives to you.
This is where the if else statement will come into play. This kind of statement
can add a lot of power to the code that you are writing and can also allow for
more than one option when the user puts in their answer. Sometimes you only
have to place in two options, but the if else statement will also be available for
different options as well. The syntax that you can write with using with the if
else statement is the following:
If (the Boolean expression)
{The statement/s you want to run if the result is true;
}
Else
{The statement/s you want to run if the result is false;
}
As you can already see with this example, it gives you a lot more power when it
comes to the if-else statement. This is a basic option with the if-else statement,
but you can add some more lines into the code to make it even more powerful.
By using these if-else statements, if the answer is false, your code will go on to
the next part of the statement to see whether or not that one is true. If there are
more than two options, it will keep going down the if-else statement until the
answer turns out true, and then it will go and display the message that comes up.
Now that we have taken some time to talk about it, it is time to look at an
example of how this will work so you can use it in your own codes:
If ( x > 0)
{
Console.Write(“This value will be positive.”);
}
Else
{
Console.Write(“The value is less than or equal to zero.”)
}
In the example above, your else clause will be hidden unless your Boolean
expression turns out to be false. It is there if the process requires it or if the value
comes out as false, but if the value is true and matches up with the conditions
that you set, then the first statement is the one that will be used.
The if-else statement is a great option to work with, but a lot of beginners may
be scared to use it because they think that it is too hard to use. As you can see
with the example above, this is not exactly true. The if-else statement really only
takes up a few lines of text and can add a lot of interaction between the user and
the program that you won’t be able to get anywhere else.

What are nested conditional statements?


In creating a new code inside of C#, you can work with an if statement and then
add another if statement inside of it. This is a process that is known as ‘nesting,’
and it is used to make a more complex program that will rely on a chain of
conditions. One of the things that you need to keep in mind when you work with
a nested conditional statement is that if you make a mistake with writing any part
of your nested statement, it will cause an error and sometimes it will be hard to
go through and fix it all.
You can technically do as many levels of this as you would like, but most C#
experts will suggest that you limit the nested statements to no more than three
levels. If you end up going above this level, you may end up with a code that is
hard to handle and is less likely to work. As a beginner, you should stick with the
three-level rule.
If you are interested in working with the nested statement, take a look at the
example below to see how they can work.
Double r = 60;
Double s = 70;
If (r ==s)
{
System.Console.WriteLine(“These numbers are equal.);
}
Else
{
If (r > s)
System.Console.WriteLine(“The value of the first variable is
greater than that of the second one.”)’
}
Else
{
System.Console.WriteLine(The value of the second variable is
greater than that of the first one.”)’
}
}
With the example that we are looking at above, you will have a few options that
will work with the if-else clause. This will allow you to pick out the command so
that the program knows what it needs to read out. This will help you to do so
much more with your program and will make it easier to make the program more
sophisticated.
There are a lot of different times when you have to use these conditional
statements in making your C# code. These will help you to add in some more
interaction between your code and whoever is using your program. It is simple to
work with, but it will help you make a complex code in your program.
Chapter 5

Creating Objects and


Making Them Work

Classes and objects are really important to how C# and other object-oriented
programming languages will work. This is a pretty simple topic that you won’t
have trouble understanding, but this doesn’t mean it’s something you should
ignore, it is actually very important that you should learn about it because it will
help you learn how all of these work. This chapter will take the time to carefully
look at how you can work with objects so that they will function the way they
should in your code.

Classes and Objects


The first thing that we will spend our time talking about are the objects which
are used in this programming language. Programming has changed a lot over the
past few years, and this has changed how programmers create their new
computer applications. The newest form of programming, known as ‘OOP’ or
object-oriented programming, is the newest idea that most modern coding
languages rely on to get the coding done. There are a lot of components that go
with this, but it basically makes it easier to sort out and use the coding language.

What is OOP?
As a beginner, you may be curious as to what OOP means and how it’s relevant
to your coding. OOP is a style of coding that relies solely on objects to get the
program to work. OOP will provide you with a model type that is based on how
things would work in the real world and then you would use this idea and
implement it in the codes that you are writing.
In some of the older coding languages, you had to concentrate on abstract ideas
to help you to get the coding done. This may sound like a great idea, but it does
make things more difficult in the long run. With OOP, you have to work with
real objects, rather than these abstract ideas, which makes the coding so much
easier. This is the approach that most modern programming languages take and it
does make it much easier for the beginner to write their own codes, create their
own program, and even solve some of their own problems they might encounter
as they go about their programming.

Objects
In this section, we will spend some time working with objects to learn more
about them. Programmers use digital objects to help represent the physical
objects that they want to place inside of their code. While you are working with
an OOP language, it is important to remember that these objects have more than
a few characteristics that you should remember. These include:
State

These are the characteristics that will define the object. These can be general or
specific.
Behavior

These are the characteristics that will declare all the actions that an object is
capable of.
For us to understand exactly how all of this will work, we need to take a look at
an example. Let's say that we are looking at a ball. The state of this object or the
traits that define its characteristics are things like its color, what the ball is made
out of, and the size. The behavior of that ball would refer to what that ball is
capable of, such as bouncing, rolling, and so on and so forth.
When you are working on an OOP language, you can easily combine the
technique and the information to process them as the same thing. The
programming object will then match up to how it would behave or look when it
is in the real world and then it will also hold onto the actions and the information
until later.

Classes
While we will discuss this a little bit more in a later chapter, it is important to
understand a little bit about what these classes are at this point. Within this
language, the ‘classes’ refer to what defines all the characteristics of the objects
from above. These classes are in charge of giving you a model or a structure so
that you can effectively define the nature of the object. These classes are often
considered the foundation of OOP languages, and they will be linked closely to
the object. Another thing to note is that each of the objects that you are using can
also represent one specific class.
Let's take a look at how this works so that it makes a lot more sense to you. For
example, we have a class that we named ‘Toys’ and while the object will be
‘Ball.’ In this sample, the ball is one instance of that ‘Toy’ class that you worked
on. However, that the class will also define the state and the behavior of all the
‘toys’ that you add to the ‘class’ including the ‘ball.’
Classes may sound complicated, and they will make the organization of your
code a lot easier to handle, many people often see them as the basis of just about
any program. The information they hold onto is meaningful for those who will
take a look inside of the class so they can understand exactly what it is. For
example, if you have a class that you named ‘Toys,’ the other users can access or
look into the class and see that all the items or objects that were placed inside the
code actually belong there. They do not have to be exactly the same, but putting
them together in the same class should make sense.
The classes function to define the behavior of an object, such as the kinds of
actions you want that object to be capable of performing. The object will also
have its own characteristics or attributes. You will see that the attributes appear
as different variables in the body of the class while the behavior, on the other
hand, is defined by the different methods that fall inside the class.
Let's take a look at how this works by examining the Toy class that we talked
about before. When these are applied, you will get the size and the color as the
attributes. To make this work, you will need to bring out and use the move() and
the stop() methods.

How to use these classes in your code


We have already spent a little bit of time talking about classes and how you can
get them to work inside of your code, but now we need to spend some more time
looking at how they work within the program as a whole and how they are useful
at changing what you can write out inside of the code. When you are working
with the C# programming language, you need to define all of the classes with the
help of the ‘class’ keyword to not only make sure that everything works but to
also help make things clear and simple.
After you have started with the code and you typed in the word ‘class,’ this is
when you should indicate the identifier that you would like to see with the
variable and the methods that would help make it certain that all of this works.
As for making sure that all of this would stay simple, there are specific parts that
you need to use since you are working with this kind of code. The different parts
that you need to add to the class when working in C# include:
Fields

These are any of the variables that belong to a particular data type.
Methods

You can use these methods to manipulate the data.


Properties

In this programming language, the properties are what will enhance how well the
fields work. The property will provide some extra management abilities for the
information and give it to the fields.
At this point, it will probably be easier if you take a look at how you can work
with making classes and how to make sure that they do exactly what you would
like. We will now have a look at an example of how this code will work and the
different theories that have been going on with it. In this example, we will use
‘book’ as the name of the class and then it will have the properties of ‘size’ and
‘type.’ The example of this code is as follows:
Public class Book
{
Private string bookType:
Private string size;
Public string BookType
{
Get
{
Return this. bookType;
}
Set
{
This.bookTyupe = value’
}
}
Public string Size
{
Get
{
Return this size;
}
Set
{
this.size = value;
}
}
public Book()
{
this.bookType = “Dictionary”;
this.size = “large”;
}
public book(string bookType, string size)
{
this.bookType = bookType;
this.size = size;
}
public void Sample()
{
Console.WriteLine(“ Is this a {0}, bookType):
Now, at first, this will look like a really complicated code to work with and you
may be worried about how you will keep all of this in order or if you can
understand how to use it at all. It is really not that complicated at all to work
with though and you can use the ideas that are inside.
With this example, the ‘Book’ class will define two different properties, the book
type, and the size. These properties will hide the values inside the fields of the
same names while the code snippet will declare two constructors that will be
generated on the Book class. This code will also create a method called Sample()
.
You can use this code for a number of different things, like adding in more
characteristics if you would like, and it doesn’t have to be limited to books, toys,
vehicles, or anything else. You can mess around with your text editor as much as
you want to try out this formula and change it around with some other classes to
make it easier to get the program to work for you.

How to create your own objects


Once you have a class in place to help you out, it is time to work on creating
some of the objects that you would like to use and place inside a class. Creating
your own object is not meant to be difficult to work with so in this part of the
book, we will take the time to have a look at the basics that you need to know to
get started.

Creating the object


The first thing that we have to do here is to create the object that you want to
place inside an existing class. To get this to happen, you need to make your own
keywords. Usually, a programmer will choose to assign the new object a variable
so that it will stay as the same data type as the class that you want to use.
Remember that doing this won’t copy the object over to the right variable, but it
will help give the variable a reference to the object that it is now assigned to. To
make sure that this actually works, use the following code to do so:
Book someBook = new Book()
This is a good example that you can use because it will take the instance of the
book and assign it over to the variable that we named ‘someBook.’ This will
ensure that the proper object will the right class as is needed.

System classes
If you are new to working with the C# language, you will find that this language
already has a library that is built right in. This library includes a lot of classes
that are kind of default such as string, math, and console. As you start to use this
language more, you must remember that the library is something that you can
easily use and access with the ‘.Net’ applications.
You are definitely going to love how the .NET framework will do the job for
you. This is because the library that you need for C# was installed ahead of time.
These classes are the parts that you can use all of the time, and they are helpful
as you start to learn some of the basics that come with this language, such as
networking, text procession, and execution. These classes are also helpful to a
beginner who has never worked in programming before because they are
prewritten and recognized by the program so you will not have to do as much
work.
One thing that you should remember when you are working with these classes is
that they will hide all the logical implementations. You need to focus more on
what your classes can do, rather than worrying so much about the mechanics
behind how they exactly do this. Because of this, the built-in classes with C# are
not something that the programmer can actually view. You simply need to use
these codes for their general purposes rather than worrying so much about how
they really work because that’s something you don’t really have to think about.

How to assign a parameter to the object


This programming language will allow you to assign some parameters to the
object that you created. This is something that’s pretty easy to work with, and
you just need to have the basic syntax in place to make sure that this will work
for you. The syntax that you need to use is this:
Book someBook = new Book(“Biography”, “large”)’;
This code will create a new object named ‘someBook’ and will assign the two
different parameters to it as well. With this adjustment, the object’s ‘type’ is now
Biography while the size is now large.
Whenever you use the new keyword, the framework of .NET can complete two
things:
It will reserve some of the memory for this new object
It will initialize the object’s data members

This is a process that will occur because of the constructor method. For the code
that we wrote above, the parameters that we set out right away are the
parameters for a ‘class constructor.’ This is what will make sure that the object
will stay inside the class that you chose to create and it will provide that object
with the right characteristics so that it works properly.

Releasing your objects


One thing that you need to concentrate on is learning how to release the object
that you are working with. Some other languages that you will work with will
make you go through and manually release the objects, but this is not something
that is required when it comes to working with C#. This means that you can
release any of the objects that are consuming up too much memory in your
system without having to go through and manually destroy them. You can just
use the CLR system that can be found inside the .NET framework to make all of
this work.
When you are working with the CLR system, the computer can automatically
detect and then release the objects that were not referenced. The memory that
was reserved for these objects is now available again, and you can use them for
some of the other objects or variables that you will create inside of your code. If
you would like to release an object, you should stop and learn how to destroy the
corresponding references as well. An example of how you would go through and
do this is the following:
someBook = null
This process doesn’t mean it’s going to delete the object, but it will make sure
that all references to that object are removed so that the CLR can go through
after you are done with it and perform the deletion for you. This is a great
process to have because it will help to limit the number of issues that occur in
your code and can get rid of some of the bugs that might show up in the code.

The constructors
The last topic that we will discuss in this chapter is the ‘constructors.’ These
constructors are basically methods that will run when the program creates a new
object. The idea behind using these is so that you can use it to initialize the data
of that new object. You won’t get anything of value to show up when you go
with this method. In addition, this constructor will use the same name as the
class that it comes from, this means you don’t have to try and match up a few
random names along the way. You also get the choice of assigning the right
parameters to this when you work with constructors in C#.
The constructors that come with C# can accept parameters just like any method
that you are using in this programming language. You can set up several
constructors in the class, but you always need to check to see if the constructors
are from different types and numbers of parameters. This will help to make sure
that each parameter is unique.
As you are working with constructors, it is important to remember that these will
run any time that you create a brand new object in your class. If you are working
with a class that has a few different constructors inside of it, you may be curious
to figure out which of the constructors are running as a new object is created in
the code. This programming language can pick out the right constructor based on
what you are working on so you won’t be responsible for coming up with all that
information. The compiler will take over so things will stay organized without
you being stressed out so much about it.
Now that we have talked about the constructor a little bit, let’s take a look at an
example of how this would work in C#:
public class Device
{
private string type;
private string size;
// A constructor without any parameter
public Device()
{
this.type =”laptop”;
this.type = “large”;
}
//A constructor with two parameters.
{
this.type = type;
this.size = size;
}
}
The parameters that we just set up can help tell the program what are the tasks or
functions that need to be fulfilled. It is also responsible for helping the C#
compiler to figure out the constructor that you would like the program to use.
Chapter 6

How to Define Classes


with the Help of C#

While we spent a substantial amount of time talking about classes and objects in
the last chapter, in this chapter, we will spend some time looking at classes in
depth. Classes are so important when it comes to working with any
programming language because they perform a variety of helpful functions, and
this is true in C# as well. So, let’s take some time to look at how to define classes
inside the C# language.

The basics of working with classes


When you are working with a programming language, the class is the part that
will define the object types and the data types that you can use at that point in
the program. The object is what will contain the information that defines the
class or the container that it is held in. These classes can hold a ton of
information, and they can be used to describe the behavior of the object as well.
These are all the behaviors that the object is capable of doing. When working
with OOP languages, you want to use methods that will help describe the
behavior of the objects.

Components of classes
When you are working with a class, some different components will come into
play to help you get these classes taken care of. There are a few different parts
that come with each class including:
Declaration

This is the line that will declare the identifier of the class.
Body

Just like with methods, the classes to have a single body. You need to define the
body right after you make the declaration. The body is the statement, or several
statements, that are found between the curly brackets. An example of this is:
class Example
{
//This is the body of the “Example” class.
}
Constructor

This is the part that will allow you to create a new object. An example of this is:
Public Sample()
{
//Insert what you want to say here.
}
Fields

These are the variables that you will declare within your class. The fields contain
the values that will represent the exact state of the object they are trying to get
to.
Properties

This part will describe the different attributes of the class. Many programmers
will write the class properties right inside the field of their chosen object.

Methods
A method is basically a named block of code that is executable. It is capable of
completing some tasks that will then allow objects to attain the right behavior. It
can also execute the proper algorithms that are present in the codes.

Custom classes
Before you decide that you want to work with a specific class, you should make
sure that you have an object that will go inside of it. You can do this by starting
with a new keyword and then all you have to do is add in the constructors that
you will need.
While you are working on the C# language, you won’t have the access to
manipulate the objects that you are creating directly. Instead, you need to assign
your objects to a variable beforehand so that you can manipulate the objects if
needed later on. Remember that to access the methods as well as the properties
of that object you need to indicate the identifier that goes along with the object
and then use your dot operator.

How to organize your classes


It is incredibly important that you can organize the classes that you are using the
C# language. There is really only one rule that you must follow to make this all
work. This one rule is that the classes must be saved as .cs files so that they are
easier to find when you want to pull them up later to ensure that the codes will
work properly.
Technically, you do have the ability to save all of your classes into one big file,
and the compiler should not have any issues with getting these to work without
errors. But many programmers prefer to save their classes in different files
because it helps them to easily find these classes later on and organize them as
needed. It is really up to you how you would like to get this done though.
Another thing that you will eventually gain some familiarity with as you
continue working in this programming language is the ‘namespace.’ This is a set
of classes that are all related in some manner. The way that they are related will
vary depending on the situation, but if examined, the way these classes relate to
one another makes sense. These can include things like structures, interfaces,
classes, and even the information that is placed inside of them. You even have
the freedom to combine several classes together into a new namespace
regardless of where they had been placed in the computer's memory.
If you are interested in creating a new namespace on the codes that you have
already worked on, you should make sure that you add in the ‘using’ directive to
make things a bit easier for you. Most programmers will find that it is easier for
them to write out the directives that they want to use inside the first few lines of
the .cs file so that they do not forget to put them there later. After you made sure
to insert this directive, you will then be able to declare the namespace.

Accessing the classes


The next thing that we will take a look at is how to access these classes. C#
allows support from four modifiers when it comes to who can access each class.
These modifiers are ‘public,’ ‘internal,’ ‘private,’ and ‘protected.’ What these
modifiers do is that they allow you to control who will be able to see the
elements that are in a particular class. Let's look at how each of these work so
you can decide which one to use when writing your own code:
Private

The function of this modifier is that will place some strict restrictions on one of
your classes. If the class is tagged as a private class, it will not be accessible by
the other classes in the code. The C# language will use this as the default
modifier if you do not place anything else there. This can help to avoid problems
in the future in case you forget to add on that modifier.
Public

You can also choose to make the class public. This means that the modifier will
tell the other classes that they have access to this class. This modifier can take
away all the limitations about how visible this class is to all the other classes.
Internal

If your code has the ‘internal’ modifier on it, this means that this class will be
accessible, but only to the files that fall in the same project.
Protected

This is the modifier that you want to use if you would like to prevent a user from
accessing the element. However, it also allows all the descendant classes to have
access to the elements of that class if they need it.
As you can see, each of these elements all works in a slightly different way
compared to one another based on how much you want your classes to be private
in terms of permitted access. If you would like to make sure that the class
remains private and that nothing or no one else is allowed to get ahold of it or
use the information, then you working in the private setting is obviously the best
for you. However, if you need other classes to have the ability to work with this
particular class, then it is just fine to change it to the public modifier.
As you go through your program, think about which of these modifiers will work
out the best for your code. If you do not place any of these modifiers before your
class, then it will default as a private class, which is not that bad of a thing. But
if you feel that one of the other options is the best for making your code, then
you must make sure that it is written in with the class to avoid issues later.

A final word about classes


The importance of these classes cannot be emphasized enough when it comes to
writing out your code. They help you to keep things neat and organized and will
also make sure that you can easily pull up the things that you need from the
code. This can make things so much simpler to work with. Your code will work
better, and you will find that writing your own codes isn’t even really that
difficult.
When it comes to picking out the objects that go with the class that you are
writing, you must remember that these objects need to make sense if you put
them together. You should have someone else, like a friend or a co-worker who’s
familiar with programming, look at the class and agree that it makes sense that
those objects ended up together. This does not mean that the objects need to be
identical, but they need to at least be related in some way.
For example, if you have a class that is called ‘Toys,’ you don’t just place the
same toy inside and leave it as it is. You could include all sorts of ‘toys’ or other
objects inside, but some rules have to be followed. This can work with any kind
of class that you would like to work with. You could have a class of things that
are colored blue, one for animals, and one for types of vehicles. As long as the
objects that go inside match up a little bit, that means you’re doing everything
right.
It is important to spend some time learning about objects because they are so
important to ensure that your code works the way that you would like. They
provide the tools to organize your code and make sure it works amazingly well.
Try out a few of the different codes that are in this guidebook, and you will
quickly see how well these work once you try making your own code.
Conclusion
Thank you for making it through to the end of this book, let’s hope it was
informative and that it was able to provide you with all of the tools you need to
achieve your goals whatever they may be.
The next step is to get started with writing some of your own codes with the C#
language. This is a great coding language to work with, and it can help you to
write out some really fantastic codes in no time. This guidebook is meant to help
you to use this language on any program that you would like and see some
amazing results.
As a beginner, you will accomplish amazing goals with this guidebook and gain
valuable knowledge in learning how to work with the C# language. We have
explored many different topics that come with this language, such as how to
work with conditional statements, how to work with classes, and what the
operators are all about, and so much more. This guidebook will help you to go
through the C# language so that you can learn to write your own codes.
If you feel like you’re ready to learn a new coding language and get started on
programming, C# is a great one to go with. Make sure to check out this
guidebook to learn all the basics that you need to know to create really useful
codes in no time at all.
Finally, if you found this book useful in any way, a review on Amazon is always
appreciated!
POWERSHELL

The Ultimate Beginner's Guide


to Learn and Understand PowerShell
Programming Effectively
Introduction
The following chapters will discuss everything that you need to know to get
started with the PowerShell program. This is a powerful coding language that
comes from Microsoft, so you know that it will work out well for you and will
help you to get the total control over your computer that you are looking for.
This guidebook will provide you with all the information that you need to get
started with PowerShell.
There are a lot of things that you will be able to do with PowerShell, and if you
like working with Windows programs, you will find that there is nothing better
to work with than PowerShell. This guidebook will talk about some of the
different things that you can do with PowerShell such as working with the
commands, working with pipelines, and even how to work with directories.
When you are done with this guidebook, you will be able to write some of your
own codes in PowerShell and be able to get your computer to behave the way
that you would like.
When you are ready to take control of your computer and see some great results
with coding, make sure to check out this guidebook to see some good results.
There are plenty of books on this subject on the market, so thanks again for
choosing this one! Every effort was made to ensure it is full of as much useful
information as possible, please enjoy!
Chapter 1

What Is the PowerShell Language?

The world of coding can be an exciting place. There are a lot of languages that
you can learn about and use. While people who have never worked with coding
in the past may think that programming is confusing, learning a new coding
language is similar to learning a new language like Greek or German. You will
start out this process by learning some of the basic words that will get the
language to go and how to form sentences (which will be known as ‘commands’
in this language) to get them to work well. This does take some time to learn,
and some are easier to work with than others, but with some practice, coding can
be so easy for you to work with.
For this guidebook, we will spend our time looking at the PowerShell language
for Microsoft. This is basically the new ‘Command Line Interface’ that you can
use on the Windows system. If you are familiar with how the Windows system
works and you like using this, then PowerShell is a great coding language to
work with. It relies on the simple Microsoft interface that you have come to
know and love and it still has all the power that you are looking for to get things
done. Now, let’s take a look at how to get started with PowerShell and how to
make it work for your coding needs.

What is PowerShell?
The first question that you may have about PowerShell is, ‘What exactly is it?’
PowerShell is a shell (an interactive user interface with an operating system) that
Microsoft developed to help with task automation as well as configuration
management. This shell is pretty powerful, and it is based on the .NET
framework. It comes with the command line shell and a scripting language so
that you can employ different tools to accomplish tasks that you would like to
get done. PowerShell also comes with a Windows ISE to help you to create
scripts without needing to type in the commands all the time.
To keep things simple, PowerShell is basically a command line interface that
works with the Windows system. There are a lot of different parts that come with
the PowerShell:
Access to the Dynamic Linked Libraries with Windows
Access to the Windows COM
Access to Windows Management Instrumentation
Access to the .NET Framework API
PowerShell Functions
PowerShell Commands
Existing Windows Command Line Tools
There are many features that you can use when you are working with
PowerShell. This system also works with other APIs as well as other
technologies that you can already find on the Windows systems. This is one of
the many reasons why PowerShell has become so popular. In addition,
PowerShell is already included on your Windows System. For those who are on
Windows 2008 or Windows 7, you will have the v2 version, and those who have
newer models will have the v3 version. If you would like to change which
version of PowerShell you have, you can do this on the Microsoft website.

What are the things that can I do with PowerShell?


While it is likely that you already have PowerShell on your computer if you
possess a Windows computer, you may be curious to know what are the things
you can do with this coding language. PowerShell is really easy to learn, and it
comes with a ton of features that work well with the Windows operating system
which will definitely keep you busy.
PowerShell was originally designed to help you automate and solve many hard
and tedious admin tasks that are present on your computer. For example, you can
use this language to look at all of the USB devices that are installed on any of
the computers that are in your network. You can also set up some tasks that take
you a lot of time to complete and have them work in the background while you
complete other tasks. Some people will use the PowerShell to identify and kill
processes that do not respond well, or you can filter out some information about
your computer on your network before you export it all to the HTML format.
That is just the beginning of what you can do when you work with PowerShell.
It is also possible to simplify and automate some of the tasks that you are
supposed to do as an admin. This coding language can be used to create some
scripts for these tasks and then can combine together a few commands to make
things easier.
Many administrators of a network will use PowerShell to help them with the
‘Active Directory.’ Since PowerShell can hold onto hundreds of commands and
you have the access to customize them, the help that PowerShell can provide
ensures that you will be able to make your network more efficient and more
productive.
To keep things simple, you can use PowerShell to make running your network
easier, without having to waste so much time and energy on doing these tasks.
While some other programming languages promise to do this, none will be as
effective as PowerShell to get the work done. Add that it works well with your
Windows systems, and you have the program that you need to get things done.

The benefits of working with PowerShell


There are a lot of different options that you can work with when you are ready to
start coding. You can work with Python which is considered one of the easiest
coding languages. There is Java or JavaScript which work well if you want to
create great websites, and so much more. So, why should you choose to go with
the PowerShell program? Some of the benefits of going with PowerShell over
some of the other coding languages include:

Easy to use and fast


PowerShell is a fast language that is really simple to use. This makes it easy for
beginners to use so they can learn how to make their coding better than ever
before.

Works with Windows


If you have worked with Windows in the past and are a fan of the operating
system, you will find that PowerShell works well with it. This helps to give you
all the security and features that you are looking for in a coding language.

Small codes
Many coding languages will require you to write out a huge code to do anything.
You could fill out a whole page or more to do one thing, and when you try to
write out a whole code, you will have to spend a lot of time and take up a lot of
space. This is not true when you are working with PowerShell. Most of the codes
in this programming language only require the use of just a few words to work it
out, which means you can write out a whole code with only a few lines.
Already downloaded on your computer
If you use a Windows computer, you will see that PowerShell is already
downloaded. But if your computer doesn’t have the version that you would like
to work with, you can visit the Microsoft store to get that changed. But all
Windows computers now come with PowerShell and the ISE that you need to
make it work so you can get started with coding in no time.
As you can see, working with PowerShell has a lot of benefits that are great
when you are trying to get started on learning how to code. You can write all the
codes that you are looking for without all the hard work, and you get to rely on
the great Microsoft and Windows products that you have come to know and
love. So, let’s get started learning how to make PowerShell work for all your
coding needs.
Chapter 2

How to Create Your


Own Commands in PowerShell

If you would like PowerShell to work for you, it is important that you learn how
to work with the commands that come with it. These commands tell the
computer how you would like it to behave. Without the proper command, the
program is not going to have any idea how to perform the functions that you
want it to perform. Working with commands in PowerShell is pretty simple, and
you will catch on quickly.
The naming convention in PowerShell is that you have to write it in the verb-
noun form. This helps to keep things consistent, and it can help you to learn it
faster while opening up the possibilities of expanding this later on. The ‘verb’ is
the action part of your command, and then the ‘noun’ will tell the command
where the action should be performed. To get the command to run in this system,
you have to bring up the command prompt, similar to what you would see with
Linux or some of the other operating systems, type in the requirements using the
syntax that we gave above, and then press ‘enter.’ If you did the process right,
you should see the right outcome come up.
There are times when you may forget the command that you would like to use
when you are working with PowerShell. This will happen as you are learning the
system or if you want to bring out a command that you do not use all that often.
The good news is that there is a simple way that you can find the command that
you would like to use. The ‘Get’ command will be there to help you out in this
situation.
By using the Get command, you are telling the system that you would like to see
the full list of commands that are available for you to use. You will then see a list
of all the commands that you can use in PowerShell, making it much easier to
find the one that you want to use. This is a tool that you will use often, especially
in the beginning, to help you to learn some new codes or to help you remember a
code if you forget it. If you would like to take it a little further and figure out
what all the commands can do, you just need to use the ‘Get Help’ command to
make this happen.

How does the help command work?


When you are working with PowerShell, you will notice that you can use a
sequence of help files that will guide you whenever you need them. It is easy to
access these help files by using the command ‘Get-Help.’ Once the system reads
this command, it will bring up all the commands that are available in this system
as well as their descriptions, so you know how each one will work. This can be
good if you really have no idea how to use the commands or which command
you would need to put into your code.
Notice that when you use this command, there is a hyphen that shows up
between the verb and the noun to help separate them and to let the command
prompt know what you would like to do. It is important that you set up all of the
commands this way so that the prompt will know what you want and will bring
you the information that you are requesting.
Let’s see how this will all work with some other common tasks that you would
need to do as the administrator. We will have a look at some commands that
would help you out with some text files. First, if you have a file on your system
that you would like to read through, the command that you should use is ‘Get-
Content.’ If this is the only file that is on your system, it will show up after you
placed and entered this into the command prompt.
Now, there are times when you will have more than one single text file on your
computer. If you use the command that we had before, the computer will be
confused as to which file you would like to look at, and it will not know what to
bring you. This has a simple fix because you just need to add a few more details
to make it all work. Make sure that you know what the name of the chosen text
file is and then bring up your command prompt. You would then type in the
command ‘Get-Help name Get-Content.’ This will return the command
description and the syntax information. Keep in mind that the part of the Get-
Content command will also return the contents of an item or return any type of
file on the system to the right place.
It is easy to go through this and change up the syntax to get it to bring up any file
that you would like on your system. You can have it bring up text on whatever
document you would like to read, bring up files that are on other systems, and
more based on the syntax and the names that you add to the code. This allows
you to have a ton of freedom when you are working with commands on
PowerShell and will help you to get things done the way that you would like.

Concepts help
As you are working with PowerShell, there may be times when you would like
to get an overview of the concepts that are found in this coding language. To do
this, you can look through the right files to find out the information that you
want. Each file will begin with ‘about,’ and then it will end with whatever topic
you are looking for. For example, you could look at the complete list of these
topics just by entering the command ‘Get-Help about*.’
If you type in the code that you saw above, you will just get a complete list of all
the concepts that are on the computer, but this could be a long list. And if you
already know the name of the file that you would like to use, it might get
tedious. To make this easier, you simply need to add in the name as the
parameter value in that syntax that we discussed before, and it will show up for
you. The command that you need in this situation is ‘Get-Help about flow
control.’ The command prompt will handle the rest.

Aliases
You may also want to work with what is known as ‘aliases.’ You may find that
some of the commands you would like to use in PowerShell are longer, and if
you have to spend so much time typing them out, it can get a little bit tedious.
The good news is that the PowerShell system will make it easier for you by
allowing aliases to refer back to some commands that you would like to use.
These aliases are just alternate names that you can give to your commands.
These aliases will take up less time and space than the original command, so
they are like a shortcut.
You can choose between using these commands and writing down the alias that
you would like to use. If you would like to use an alias for your code, you can
just type in ‘Get-Alias.’ This will tell the command prompt that you want to see
the aliases that you would like to use and it can save you some time.
Now, for a bit of clarification, it is important to note that the current session will
refer to the current connection with PowerShell. When you first open up
PowerShell, a brand new session will be created. This session will remain in
effect until you close and exit out of PowerShell, which will effectively end the
connection as well as the session. One thing that you can do during your sessions
on PowerShell is to look under Get-Alias and see what other aliases were created
by users during that session as well as any aliases that are defined in the startup,
user configurations, or profiles.
If you would like to view a specified command alias, you will have to identify
the specific ‘Get-Alias’ command. For example, if you would like to view the
aliases that you can use with ‘Get-ChildItem,’ you will need to enter the
following command:
Get-Alias |
Where-Object {$_.definition
-match “Get-ChildItem”}
At this point, you probably feel confused as you look at the code because there
are some commands in there that you do not understand. We will go through
those a bit more throughout the guidebook, but the part that is important right
now is that the outcome you get from this command is directed to the ‘Where-
Object’ command. This allows you to filter out any results that are not matching
up with what you would like. It is possible to do this with any alias or command
that you want. You simply need to go through and change the name around to
what you are looking for.
One thing to note here is that PowerShell will utilize three aliases when it is
working with the Get-ChildItem, and these would include ls , gci , and dir . Each
of these will provide you with the same results so you can use the one that you
would like. So, the three codes that we wrote below will work the same way, so
you get the choice of which one to go with:
Get-ChildItem c:/windows
dir c:/windows
ls c:/windows
gci c:/windows
If you are feeling a bit adventurous, you can create one of your own aliases
inside the current session by using the command ‘Set-Alias.’ It is pretty easy to
do. So, let’s say that you want to create an alias for Get-Content and you want to
name it cnt . All you have to do is run the command “Set-Alias cnt Get-
Content.”
As you can see from the example above, you have created a new alias, and you
could use the shortcut cnt any time that you want to use the Get-Content
command in the system. This new alias that you created will stay active until
you end that session in PowerShell or when you exit out of the system. If you
accidentally exit the program and you want to use that alias again when you
write another code, this is easy to do.
As you can see, working with the command language in PowerShell is not meant
to be difficult. Many coding languages are hard to work with, and you may
spend many weeks or longer trying to learn just the basics that go with it.
However, you will find that even as a beginner, working with PowerShell is easy
and you can catch up with using the syntax and the commands in no time.
Chapter 3

Outputs and Pipelines in PowerShell

Now that you have a good idea of what the commands are all about and how
they will run the program, it is time to move on to something else that will help
your program become more effective. Since commands won’t always have the
power that you need to get things done, PowerShell has created what is known
as a ‘pipeline’ to make things easier. These pipelines are useful because they will
link your commands together to accomplish more complex tasks and other
things inside the code compared to what the commands can do on their own.
This chapter will focus on showing you how to work with pipelines inside of
PowerShell so that you can add some more power to your code.

How to work with pipelines


As we have stated in this guidebook, PowerShell is a system that is based off a
set of commands. These commands can be passed on to objects with one
command and be moved over to the next object the same way. Each command
creates an object before it sends that object down the line so that the following
command can pick it up. The next command to pick it up will then utilize the
object as the input so that it can create its own output before sending that part
down to the next command. This is a continuous line that will keep on going
until it reaches the right conclusion. This chain of command will sometimes be
really long, although there are times when it can be short, and it creates a
pipeline. This is shown with the help of the (|) symbol.
In your traditional command shell, the results coming from the pipeline will all
be returned at the same time. This means that the final result for your pipeline
will be shown in one result rather than showing you each individual step that
occurs in the pipeline. But when you are using PowerShell, you will notice that
things will work a bit differently. For this one, the results will be sent through the
pipeline, and when just one of the commands ends up with a result, it will be
accessible right away.
Let’s take a look at an example of how this works. If you are using the ‘Get-
Service’ command, you will get a whole rundown of each service that is in the
framework. Once all of this is done, you can see the command will give back the
display, the admin name, and the status of the system.
To make it go further, instead of just seeing the entire rundown of the service on
the system, you will get a return of the list of services that you have running and
working on the system. To make this happen, you have to use both the ‘Where-
Object’ and the ‘Get-Service commands.’ You would be able to use the following
syntax to make this pipeline happen:
Get_Service | Where_Object {$_.status-eq ‘running’}
As you have noticed, the pipeline operation is in place, and it is used to show
that two commands need to be connected together. The Get-Service part of the
code will produce an object that contains a full list of information that is service
related. When you use this symbol, the object will then send itself over to the
Where-Object command as the input. The Where-Object command will filter out
that information based on what you placed into the brackets. This ensures that
you will only receive back the information that you need.
Now, with this process, if the system takes a look at the information that you
placed inside the brackets and determines that it is true, then the object will
continue on through the pipeline. But, if there is something in the information
that is seen as false, this information will be filtered out so that you only end up
with the information that you actually need.
With the example that we just did, we used the operator -eq , which means that
the status property must be equal to the running string. You must remember that
you can see all of the properties you can use inside the help files while the
‘Status’ is a part that will generate an object with the help of the ‘Get-Service’
command. When you have at least one object pass through the pipeline (you can
actually do more), you will be able to access the properties similar to the process
you did with the Where-Object command.
Now, we will take a look at what we have to do if we wanted to limit the
information that we received. Sometimes, you will get a lot of information sent
back to you, and this is not a good thing if you are looking for something in
particular. You do not want to spend all that time reading through the
information and hoping that you will find exactly what you are looking for. The
good news is that you can expand the pipeline so you can put in the right
information and get the right results at the end. The syntax that you can use to
make this happen is this:
Get-Service |
where {$_.status -eq ‘running} |
select displayname
With the example that we listed above, the object will be received first by your
Select-Object command, after it was sent there by the Where-Object command.
This illustration will utilize the ‘where’ alias that we talked about before, so you
do not need to list out the Where-Object all the time. The same thing is true
when we are talking about the ‘select’ alias as well. This helps to shorten up the
code that we are looking at a little bit and makes it easier to work with.
When you are working with all three pipelines, you must remember that you
need to work on the process of operating with objects. This means that all the
commands that you add to the syntax will create their own object, which will be
received by the next command. The final command that you wrote will have to
generate the object, which will then output the results that you are looking for.
Now that we have taken a look at how all of this will work, it is time to move on
to learn how you can use these objects and their properties so that you can make
refinements with your illustrations in PowerShell.

How to work with format output


Before we get too far with this option, it is important to realize that PowerShell
will automatically format illustrations based on the data type that you placed in
the output. So, if you use the ‘Get-Process PS,’ you will end up with an
illustration that you can use to return any data that is found on the ‘PS’ process.
This will display the output of the command, and if you want something else to
show up, you must use the pipeline, along with a few other supported output
commands, to make this happen. The four main commands that you would use
to make this happen are:
Format-Table
This is a command to use if you would like to show off the returned data within
a table. This is often the default option that is used with many commands, so it is
not always necessary that you specify the output.
Format-List
This is a good command to use when you would like to return the data in a list
form so that you can look at it this way.
Format-Wide
This is the command that you will use to get the data to return to a wide table
format. This is a table that will include just one value for each individual item
that is displayed.
Format-Custom
When you are using this command, you will be given data that comes from a
custom format, which is based on the configuration data that you saved on the
computer. When you use this format, you will notice that it comes back in the
file format of .px1xml . Any time that you would like to update it, you can use
the ‘Update-Format Data’ command.

How to control the output


Unless you took some special steps to override this, the default output will be
applied to your format before it is sent to the console window that will show
your illustration. You do have the power to override this by using the four
formatting options that we talked about before. In addition to those four options
that we talked about, you can also control where you send the output. Some of
the commands that will make this a little bit easier include the following:
Out-Host
This is the default command so you don’t need to make any specifications with
this one. It sends the output over to the console.
Out-Default
This is another one that doesn’t have to be specified in the process. It sends the
output to the default formatting command that is set up. It delegates this process
to the Out-Host.
Out-File
This is the command that directs the output to the file you chose.
Out-Null
This is the command that deletes the output. When you use this command, you
will see that the PowerShell console won’t show any results.
Out-Printer
This is the command that will direct your output to the printer that you specified.
Out-String
This is the command that will convert your object into a string array.
Remember that if you are working with your output and you need some more
help controlling it, or you would like to change it up a little bit to get it to do
something else, it is a good idea to use the help files to get the assistance that
you need.
If you are interested in using some of the commands that are listed above, you
just need to add them to the end of your pipeline. Let’s take a look at an example
of how this works:
Get-Process PS |
Format-List |
Out-File C:\SysInfo\ps.txt
When you use this code, you will see that the output won’t be displayed on the
console of PowerShell. Rather, the system will save the contents to the file that
you specified in the format (you can change it as you see fit). You do need to
make sure that you are sending output files that make sense. Sending some text
over to a .bmp file would not make that much sense, and it will just result in an
error without letting you view the output when you try to open the file later on.
In addition to letting you direct the output of a file, the Out-File can be useful for
allowing you to replace or append content that is already with the current output.
If you do not direct it to do otherwise, the PowerShell will replace the existing
content because this is the default function of the program. If you would like to
append to the output file, you simply need to add the ‘-append’ switch to this
command so it would look like the following:
Get-Process PS |
Format-List |
Out-File C:\SysInfo\ps.txt
-append

How to set the output


The next thing that we will learn is how to set your output. In addition to making
some changes in the input, there will be times when you want to control how the
output works as well. You can do this with the help of the Sort-Object command.
This command is in charge of taking the input of the objects of your pipeline,
and it will sort them out based on the criteria that you set.
While you will usually see that PowerShell will stream the results with your
pipeline’s help, this command, the Sort-Object command, will wait until all of
the results are retrieved, and then it will sort them out. This will stop the
streaming process so that the sorting can happen first. This may not seem too big
of a deal when you are starting out and when you work with smaller returns, but
it will really make a difference when you are working with a ton of data at once.
Even though this command may slow down your computer, it is still one that
you should know how to use. For example, if you are looking at a folder and you
want to get a list of all the items that are inside, you can use the Sort-Object
command to make that list. A good example of doing this is the example below
where we will list out all the items that are in the C:\ Windows folder:
dir c:\windows |
where {$_.length -gt 500000} |
sort -property length
-descending
With the example that we did above, the command will pass the object from the
dir alias down to your Where-Object, which will be shown with the ‘where’
alias. In this command, we can specify that we wanted to get results that were
larger than 500,000 (this is shown in the part for -gt ). The object is then sent
along this pipeline to the ‘Sort-Object command.’ When it reaches this particular
part, it will start to organize based on any criteria that you listed. With this one,
we added in the -descending to tell the system how we wanted things to show
up. You can choose whether you would like to have this in or not.
Now, the formula shown above is pretty simple to work with. It will provide you
with all the information that you were looking for in the system while it also
goes through and makes sure that it is sorted out. Of course, you can add in some
other specifications if your code needs it and the PowerShell system can be used
to make these changes for you.
While it may sound complicated since you’re still getting started, these pipelines
can really make significant changes to the code that you are working with. They
will not limit you to what you can add to the system, and you can send the object
through several requirements before it shows up on the screen. This is a great
way to save some time, and you can use it easily in your code, even if you are
just a beginner.
Chapter 4

The Operations and Wildcards

The previous chapter was all about the pipelines that come with PowerShell and
how you can use them to streamline the whole process that comes with this
program. These pipelines will help you to sort out information and will make it
easier to change the files that you are using. You are basically using the pipelines
to connect together a string of commands so that you can filter out the objects
that you want and then that information will come up on the screen.
If you have ever worked with programming in the past with another language,
you have noticed that they all hold onto several operations. These operations are
important because they are used to create some expressions inside of the
illustration that you are making. This is something that you will see inside of
PowerShell, they are just a bit different than what you will find in the other
programming languages.
There are quite a few operators that are available in the PowerShell system you
can use, and you have already seen some of them in the codes that we have
written so far in this guidebook. Let’s start out this chapter with a look at some
of the operators that are available on PowerShell and how you can use them in
your own commands.

Operators that work for comparison


There are a number of operators that you can use inside of your code. The first
type that you may be interested in are the comparison operators. These operators
follow their name and are used to compare values. During the times where your
comparison is placed inside of the expression, PowerShell will compare the
values that are to the left and then also the ones that are to the right of the
operator. There are a lot of comparison operators that can make a difference in
your code, but these are the most common ones:

Eq
Equal to.
-ne
Not equal to.

-gt
Greater than.

-ge
Greater than or equal to.

-lt
Less than.

-le
Less than or equal to.

-like
Uses wildcards to find the matching patterns.

-notlike
Uses the wildcards to find the nonmatching patterns .

-match
Uses regular expressions to find matching patterns.

-notmatch
Uses regular expressions to find the nonmatching patterns.

-contains
Determines whether the value on the left side of your operator has the same
value as the one on the right.

-notcontains
Determines whether the value on the left side of the operator doesn’t have
the same value as the one on the right.
-replace
This one will replace part or all of the value that is on the left side of the
operator.
You can work with these operators to help make the comparisons that are needed
inside of the PowerShell system. You will need to study each one to determine
which will work for your needs. If you would like to make this system return all
of the files that are in a folder and that are under a certain size, for example, you
will need to work with the -lt operator. On the other hand, if you would like to
make sure the file is larger than a chosen side, you would work with the -gt
operator. As the programmer, you will get your choice of which operator you
would like to use so make sure to choose the one that works for your codes.

What are the wildcards?


Here we will take a pause and look at what is known as the wildcards inside of
PowerShell. For these, let's say that you are trying to search for an item that is in
one of your files, but you are not sure about the name of the file that you want to
use. This means that it is time to create a new expression that can compare a few
values together. What you can do with this situation is to bring out a wildcard to
use as an operator or use it as the compared value. There are a few different
wildcards that you can choose to use on PowerShell including:

(*)
This will match zero or more of any character.

(?)
This one will match any one character that you type out.

[char-char]
This one matches a range of sequential characters.

[char…]
This one matches any one character in a set of characters that you defined.
These wildcards look similar to the -notlike and the -like comparison operators
that we talked about earlier and they can be used to help you find whatever files
you can use, even if you are unsure about which file you want to use. To see the
code and understand how this should work, look at the following:
et-process |
where {$_.company -like “*google*”}
In the above code, the asterisk is the wildcard, and it is used to match either zero
or more of the characters. This will help you get some good results, even if you
are not able to pick out the exact name of the file. This is true even if the folder
is stored under a different variation.
PowerShell can also complete regular expressions with our code. These regular
expressions are based on the classes of regular expressions that you can easily
find in the Microsoft .NET framework.

How to work with logical operators


The third type of operator that you may want to use in your code is known as
‘logical operators.’ So far, we are looking at operators that can create a condition
and will then give us an output. However, there are times when you are working
with the PowerShell program, and you have to work with expressions that have
at least two conditions. This can be found when you are working with multiple
comparisons that will determine whether your program should take action or
stay still.
Multiple comparisons may seem complicated in the beginning, but to get them
done with one expression you just need to use a logical operator and then link it
to a condition. The logical operators are used to help specify what logic you
would like to implement on your multiple conditions evaluation. There are
several logical operators that you can work with, and these include the
following:

-and
This is when both conditions need to be true before the expression is
evaluated as true.

-or
This is when one or both conditions need to be true before the expression is
evaluated as true.

-not
This is when the specified condition needs to be false before the expression
is evaluated as true.

(!)
This is when both the conditions need to be false before the expression is
evaluated as true.
To get a good understanding of how these logical operators function, let’s take
some time to go over the following example:
Get-Process |
where {($_.handles -gt 500)
-and ($_.pm -ne 0)}
Let’s take a look at the code above. This one is working with two conditions and
both are placed inside the parentheses. With your first condition, it is used to
help specify how many handles need to be bigger than the -gt . In this option, it
is 500. In the second condition, you can specify that the paged memory won’t
end up being 0. You can use the logical operator to combine the two conditions
together.
Since the -and operator is helping to connect these two expressions, both of
these expressions need to be true. Only if the document or the file matches up
with both of the conditions will it show up on the console. If the document will
only match up with one condition or the other, they will not show up on the
screen. It does not matter which condition is met and which one is not. This
helps keep the amount of information that you see on the screen down to a
minimum. If it does not match both of the conditions that you set, then it will not
show up.
Another thing to keep in mind is that you do have the option to work with the -or
operator. The -or operator can be placed into the formula like you would with
the other logical operators, but they will work in a slightly different way. Let's
take a look at a code and how this operator will affect it:
Get-Process |
where {($_.handles -gt 500)
--or ($_.pm -ne 0)}
Now that you took that other code and changed it out for the -or operator, the
system will provide you with a different result than what you got the first time.
This is the operator that you want to go with if you want to expand the amount
of information that you are receiving. With this one, if the file or the document
matches either one or both of the conditions, it will show up on your screen.
Since the document or file only needs to match up with one of the conditions
rather than both of them, you end up with a lot of information to show up. It
doesn’t matter whether they meet both of these conditions or not, as long as they
meet at least one of the conditions, they will pass inspection.
Now, let’s look at this a bit further and see what will happen if you can add
together the -and operator and the -not logical operator. Let’s take a look at the
code first:
Get-Process |
where {($_.handles -gt 100)
-and -not($_.company -eq
“Microsoft Corporation”)}
With this example, we are telling the program that we do not want the handle to
count up anything that is bigger than 100. We are also telling it that we are
looking for a company name, but the answer can’t be Microsoft Corporation.
This line of code will go through and return illustrations that are not related to
the Microsoft name.

Arithmetic operators
You will probably recognize a lot of the operators that are listed under this
category. If you have done some form of math in the past, and you probably
have, these will look pretty familiar to you. With the PowerShell language, you
can work with some mathematical operations to get the code to work the way
that you would like. You simply need to make sure that these can all go together
and that it will make sense for the code that you are writing. Some of the
arithmetic operators that you can work with are the following:

(+)
This will add two values together.

(-)
This one subtracts one value from another.
(~)
This takes a value and converts it into a negative number.

(*)
This one multiplies two values together.

(/)
This divides two values.

(%)
This one returns the remainder of numbers that you divided.
The arithmetic operators are some of the easiest ones that you can learn about in
the PowerShell language. You can use them to add things together, to link strings
of text together, and so much more.
Working with these operators adds a lot of functionality to the code that you are
writing in PowerShell. You get to compare things, find ways to look up
information on your computer, and so much more. Make sure to check out some
of the operators and learn what they mean so that you can use them in your own
code.
Chapter 5

Working with Strings


and Quotes in PowerShell

There are a variety of syntaxes that you can work with when you are using
PowerShell to make a code. The majority of these syntaxes add in some kind of
string value. These are passed over to the commands as an argument. You will
see that the strings are sometimes enclosed in a single quote, but you can work
with a double quote as well. This chapter will focus on strings because it is
important to know how they will work inside of your code.

String values
When you are writing your code, any time that you add in some quotes around
the text that you are writing, no matter what you are writing, PowerShell is set
up to see it like a string value. With this in mind, as long as the text does not add
in any special characters or uses ‘scalers,’ you can choose whether or not that
text is surrounded by double or single quotes. Special characters all have some
different rules, but we will discuss that later.
When you are working with regular strings, the single and the double quotes
both end up meaning the same thing. The important part is that your text should
not have any special characters in it. It also matters that you start and stop the
quotes the same way. It will not work if you start the string with single quotes
and then end it with double quotes. We will take a look at two examples below.
Even though they look a bit different, they both mean the same thing in
PowerShell:
Write-Output “String in quotes.”
Write-Output ‘String in quotes.’
Also, there are times when you might want to use a quote within your string.
This will work a bit differently than before. You have the freedom to choose if
you want to put a single quote within a double quote or a double quote in a
single quote like the following:
Write-Output “String ‘in’ quotes.”
Write-Output ‘String “in” quotes.’
If you mix these around and do it the other way, such as having a double inside a
double with the quotes, you will find that the system will not read it the same
way. Here are two examples of what you should avoid doing when it comes to
adding a quote within a quote.
Write-Output “String “in” quotes.”
Write-Output ‘String ‘in’ quotes.’
If you decide to type both options into your PowerShell system, you will find
that they are interpreted in different ways. With the last two illustrations that we
wrote, you will see that in this return the quotes will not be displayed and there
is a new line that will show up. This will happen since PowerShell interprets that
one string is actually multiple strings and this ends with a line break.
Whenever you add some quotes to your code, you must make sure that you are
writing the quotes the proper way. It is a good idea to always check these to
make sure that they all match up and that you are not missing out on anything. If
you forget to do this or if you have one that’s missing a vital component, you
could end up with a loop that will not end, depending on where you made the
mistake. With this situation, the loop will be stuck, and it will keep asking for an
entry, no matter what kind of answer you place inside.
If you are working on the program and you miss out on a quote, you may end up
with a loop that keeps going on, and you will have to go back to the command
prompt to get it fixed. A quick way to do this is with Win + R, then type in cmd
or cmd.exe and press enter, so you can go through and fix the mistake.

How to add in special characters


With the examples that we have been talking about so far, you can choose which
type of quote you would like to use. In those examples, you can work with either
one because they basically mean the same thing. You just have to make sure that
you used the same type of quote at the beginning as well as at the end of your
string.
In some cases, what you chose will matter. There is a distinction that comes up
with the double and the single quote. The single quote is the one that handles the
string literally while the double quote will help you to escape any special
characters that show up.
When the special character is preceded by the ‘`’ or the ‘backtick,’ it takes on a
specific action that cannot be accomplished without these symbols in place.
Some of the special characters that you may need to use when you are working
in PowerShell are:

`0
This will insert a value that is null.

`a
This will send an alert (which can be in the sound of a beep or a bell) to the
speakers of your computer.

`b
This one inserts a backspace.

`f
This one inserts a form feed.

`n
This one will insert a new line for you to use with the text.

`r
This will insert a carriage return.

`t
This will insert a horizontal tab.

`v
This inserts a vertical.

`’
This inserts a single quote.

`”
This inserts a double quote.
One of the best ways to see how this concept works is to put into action. The
illustration below is one with a few characters that have escaped. This is done so
that you can see how the text will be displayed on your console:
Write-Output (“`n `tText includes: + `
“`n `t” escaped`” characters. ‘n”)
The first character that will escape this illustration is the ‘n.’ Then the next one is
the ‘I’ which will end up with the ab being inserted into your writing. Notice that
the backtick that we used at the first line is not the escape character, but it can be
used to show that your illustration will continue on. The double quotes will then
show up around the escaped character, and they will then have a backtick ahead
of them so that you can get the double quotes to show up at the output as well.
If you spent time trying to escape these characters even though they were within
a string that was enclosed with just a single quote, then the backticks and the
special characters won’t show up on the output. This is because the single quotes
will handle all the information literally. So, if we went with the single quotes
rather than the double quotes, you will use the following syntax:
Write-Output ‘`tindented `n `twords’
If you take the time to place this on the console, you will just get the same thing
to show up on the console because these strings only take the literal meaning.
This is something that you should take note of because, in some of the older
versions of PowerShell, you were allowed to do this with the single quotes, but
this is something that was changed in the newer versions so make sure you use
the right quotes.

System_String object members


Any time that you work with strings inside of PowerShell, it is important that
they are handled in the same way that the System_String objects are. This is a
good thing because it provides you with a ton of extra methods and properties
that you can work with. As we spent some time talking about earlier, the ‘Get-
Member’ command is used here to help you to retrieve the members of an object
as they are pushed through the pipeline that you created. Since the string also
passed just like with what happened to the objects, you can use the same
command with the string. A good example of how this will work is the
following:
“test output” | Get-Member
When you add this into your compiler, you can see that the string can support at
least a few methods. These methods could include options like ‘GetType’ and
‘Substring.’ You can also go and scroll through the information a bit to find out
the length property, which will let you know how many characters are already
present in that string.
Let’s take a look at how this could work. For this one, ay that we want to take a
look at the Substring method and we would like to use your Get-Member
command like we talked about above to help you to get the information. a good
example of making this works includes the following illustration:
“test output” |
Get-Member Substring |
Format-List
After you go through and run this illustration, you will observe that there are
details which indicate how to utilize this method properly. There are also two
styles of approach that you can use when you call this method. They include:
System.String Substring(Int32 startIndex)
System.String Substring(Int32 start Index, Int32 length)
In the first option, you provided the target string as well as an integer. This
integer is used to specify the position from where you want the substring to start.
This will cause the substring to have a return that starts in the right position and
then it will continue on until it reaches the end of the string. This makes it easier
if you would like to look at the whole string but want to start from a certain
location. So, for what we are talking about, if you chose to go with the first
option, you could type out something like the following:
(“test output”).Substring(5).
This is a good one to work with because it allows you to have the test output
come up and then it will start with the position of five on your substring.
Remember that you can place just about any number that you would like here to
make sure that the program starts right where you need it to. Of course, you have
to make sure that you are putting the ‘test output’ in parentheses and that your
period will come right after the method name so that it all works.
With the example that you worked with above, there are two methods that you
can use. So, now it is time to take a look at how that second one will work. With
that second one, you will provide the target string and the substring’s starting
length and point. If you want to make sure that you will start at a specific spot on
the string, and you only want to let the program read a few lines of it, the second
method is the one that would work the best for you. A good syntax that you
could use is this:
(“test output).Substring(0,4)
With that syntax, you can look at your output, which will start at the beginning
since you used 0, which is considered the starting position. It is also set up to go
over four characters. It is also possible to change the numbers and get them to do
the number of characters and the starting point that works the best for you.
As you can see, there is a lot of power that comes into working with the
PowerShell system. You can use some of the information that is found in this
guidebook to make it easier to work with some of the codes that you want to
write.
Chapter 6

The Drives and Providers

As you are working with PowerShell, there are many different files and folders
that you can choose from. But first, you must make sure that you are providing
the system with the right path name. The pathname usually starts with the simple
C:\ and then it is followed by the remainder of the name that comes with the file
or the folder that you want to work with. Any time that you would like to find a
specific file system, you should double check that PowerShell needs to get the
right name of the drive so that you can bring it up without too many issues.
Another thing that you will like is that some drives are not on your computer or
on the file system driver but are supported by PowerShell so that you can get
more storage and information to complete various tasks. A good example of this
is the ‘scaler’ drive. The scaler drive helps you get ahold of the built-in scalers
that you can work with on PowerShell. Let's take a quick look at some of the
other drives that you can use with PowerShell and how you will be able to
access them.

The PowerShell Providers


One more thing to keep in mind is that you need to work with a core which can
be found in the data store inside of the PowerShell provider. One provider that
you can work with is the Microsoft .NET and this layer shows up between the
PowerShell and the data that you need to make sure that you can connect to the
data stores through this service. For example, you can use your ‘Get-Children’
command to access a lot of information including the registry, certificate data
stores, and file systems.
Many providers are already built into this program. If you want to have a look at
the complete list of all these providers, you could just write out the command
‘Get-PSProvider | select Name.’ Some of the great providers that you can find
inside of PowerShell include the following:

Alias
These are the aliases that you can use to call the various commands that you
want to use inside of PowerShell.

Certificate
This is a process through Windows that is for digital signature certificates.

Environment
This is a Windows environment scaler.

FileSystem
This is the Windows file system drives, files, and folders.

Function
These are the PowerShell functions.

Registry
This is the Windows registry.

Scaler
These are all the PowerShell scalers that we talked about earlier in this
guidebook.
As you look through this list, it is easy to see that some of the processes are
available with the help of the Windows programming, which shows how well
these two programs work together. And when they do come together, you can get
all the benefits of both at the same time. These providers are important because
they are a huge part of the coding process, but you will not see them inside of
PowerShell all that often. This is because you are more likely to see the drives
that are inside your system, and these will help you to access the provider even if
you don’t need to see it.

What are the built-in drives?


The first thing that we will have to do here is to take some time to look at the
PowerShell drives that are found automatically inside the PowerShell system.
These drives are utilized on a regular basis to return data from your providers.
Basically, the file system data is exposed to the PowerShell drive that
corresponds to that Windows drive. The C drive will then be able to access the
data by a file system which will then expose the Windows C drive to the system.
A good example of the code that you can use to make all of this happen looks
like the following:
Get-PSDrive | sort Provider, Name
With that illustration above, you can sort it by the provider first and then you
will receive the name. This will make the sorting a bit easier because all of the
providers are grouped in together, and then you can take a look from there to see
how many drives each provider can hold. In the illustration above, you will also
see that the root information you can use to help you locate the target data store
is also displayed.
If you are taking a look at this and you would like to get more information on the
drives, you would just need to use the Get-PSDrive command and then type in
the information that you are looking for to make it work. So, if you are trying to
format a list, you could type out the command ‘Get-PSDrive Function | Format
List’, and it would all be done.

How to create your own drive


While there are a ton of drives that you can choose from when you use
PowerShell there are times when you might feel those drives are not exactly
what you would like for your program. This is usually when you want to create a
new drive on the system. These are drives that are based at least a little bit on the
providers that already exist on your PowerShell, which means that the process is
a bit easier to handle. But, you can use this information to make something that
is completely new.
Let's try making a new drive for PowerShell. First, you need to use the New-
PSDrive command like you did before. Let's take a look at an example of a
syntax that we would use while working on the drive named ps .
New-PSDrive -Name ps
-PSProvider FileSystem -Root $pshome
With the illustration that we just worked on above, you will notice that it will
take some time to identify the name that you would like to call the new drive
with, and it will keep going so that you can name both the provider and the root.
When you run this particular illustration, PowerShell knows that it needs to
create a new drive. Once it is done, PowerShell will display the information that
you need, so you see what is on the drive.
At this point, you will notice that any information that shows up always include
the root name, rather than the traditional scaler name. After you finish writing
out the new drive and creating it, you can use it in the exact same manner that
you would use the built-in drives. You just need to make sure that the locale is
changed for operating that new drive, and you can do this with the following
syntax:
cd ps: \
There are also times when you have to remove or delete a drive that you created
or defined, and you just need to use the ‘Remove-PSDrive’ command. It is
important to keep track of the drives that you are in because you can’t delete a
drive that you are currently working on. So, once you change the operating
locale, you can use the following illustration to remove that drive:
cd C:\; Remove-PSDrive ps.
As you are working on this, it is important to remember that when you create a
new drive, it will only stay valid during the session that it was created. This is
helpful because you don’t need to go through it after you are done with the
program and delete or otherwise remove drives or processors unless there is
some other reason for doing this because they will automatically do this when
you close it out. It can be a hassle if you are working on several systems that
need the same new drives, but it does not take long to create these at all.
Creating these new drives will help you to determine where you will work inside
the PowerShell system. You get the choice of creating your own or using one
that is already a part of the program. Use the steps above to help create a device
of your own so that you can get the hang of this and learn how to make it work
for your own coding needs.
Conclusion
Thank you for making it through to the end of this book, let’s hope it was
informative and that it was able to provide you with all of the tools you need to
achieve your goals whatever they may be.
The next step is to decide when you are ready to start working in PowerShell.
There are so many cool things that you can do once you learn this programming
language and with the help of the powerful Windows system, it will work out for
you in no time. If you feel like you are ready to start learning more about
PowerShell, make sure to check out this guidebook today!
Finally, if you found this book useful in any way, a review on Amazon is always
appreciated!
PYTHON

The Ultimate Beginner's Guide


to Learn and Understand Python
Programming Effectively
Introduction
The following chapters will discuss everything that you need to know to get
started with working on your own Python code. This is a great coding language
to work with because it is fast, simple enough to read, you can learn how to use
easily, and it still provides you with all of the power that you need to get things
done. There are no other coding languages that are quite like this one, and this
guidebook is going to show you how to get started on coding with Python.
Inside this guidebook, we will explore a lot of the different things that you need
to know to get started with coding in Python. We will look at some of the basics
of Python and how to download it, before moving on to some actual code
writing. This will include things like how to work with objects and classes, how
to handle exceptions, the importance of the conditional statements, and you will
even learn how to create some of your own loops. All these parts will come
together to help you write some amazing codes using the Python programming
language.
There are a lot of great coding languages out there that you can work with, but
none of them can compare to working with Python. Make sure that you read
through this guidebook carefully so you can learn how to write some of your
own codes with this amazing language today.
There are plenty of books on this subject on the market, so thanks again for
choosing this one! Every effort was made to ensure it is full of as much useful
information as possible, please enjoy!
Chapter 1

What Is Python and Why Is It a Good Programming


Language to Learn?

Learning a new programming language can be a great experience. You may want
to learn it so you can know more things about your computer and understand
how it works, how a website works, and perhaps you want to learn so you can
create your own applications and programs. But if you have never worked with
your computer in this way or with coding in the past, then it is hard to figure out
how to get started. With a little search, you will notice that there are many
coding languages available that you can work with besides Python. From Java to
C++ and so much more, it’s hard to determine which coding language is the best
for you.
As a beginner and someone who has never done anything with coding in the
past, Python is one of the best coding languages to work with. Python has long
been considered a beginner's language because it is so easy to learn and you will
be able to understand it right from the beginning. This is just one of the many
reasons why you should choose to work with Python. You will also like there is a
large active community devoted to this programming language and what’s good
is that it’s open source so you can get started without literally having to pay
anything. This language will also work on any operating system so it won’t
matter which computer you want to use the language on.
Despite being the coding language that beginners like to work with, this doesn't
mean that there aren't a lot of advantages that come with working with this
language. Python on its own is capable of writing great codes in the process, and
you can also combine it with a few other languages so that you can create as
many strings of code that you like. Now, let's take some time to look at Python
and all the things that you need to know to get started on using this coding
language.

Why should I learn Python?


As we mentioned before, there are actually a lot of different coding languages
that you can learn about and use. So, if there are a lot of choices out there why
would you want to go with the Python coding language in the first place? Many
people, both experts, and beginners all choose to go with Python because it is
easy to learn, easy to read, and it is capable of creating large, challenging codes
that you might want to write. There are a lot of different reasons that you would
want to work with this coding language, and these include:
Simple enough to read
You will find that Python is a programming language that is very easy to read,
even if you are a beginner. In fact, when it is compared to some of the other
coding languages, it is one of the most readable languages. Since this is an easy
coding language to go with, many beginners like that they can catch on so
quickly and that they will understand what they are doing in no time.
Free
Another benefit of going with Python is that it is free to use. There are some
computer coding languages that you would have to pay for so you can use them
and this can be quite expensive especially if you want to learn how to use more
than one of them. Python is free to use, so you don’t have to worry about this
problem.
Fast
Even though this language is easy enough for any beginner to learn, Python is
still considered one of the high-level languages that you can learn about. This
means that when you make a program and generate your own codes by using
Python, you will see that the execution is nice and quick. There are some coding
languages that are harder to work with or can’t go as fast as you want them to,
but this is a problem you won’t have when using Python.
Works on a variety of platforms
You can work with the Python language no matter which platform you would
like to use it on. Linux is the operating system that a lot of people will choose to
go with but you can still work with Python even if you are on a Windows or Mac
computer. This is great news because it means that you can actually use Python
without having to make any major changes to your current setup.
A big library to work with
Once you start to get familiar with Python, you will notice that it comes with a
large library. This is good news for beginners because the library is what
contains all the functions, codes and other things that you need to make the
language work for you. This library will help make sure that you can do some
useful things when trying to make your own code.
A large community
Whether you have worked with coding language in the past or not, it is nice to
know that there is a large community of Python users that will help you out if
you ever get stuck. Any time that you need some ideas like a new project or if
you just have a question, or if you want to learn something new, there is a library
of information to provide you with the information that you need to help you get
started.
There are a ton of people, both beginners, and experts, who use the Python
language over other programming languages because unlike those, it is simple
and easy to work with. Whether or not you have worked with a coding language
in the past, you will find that Python may just be the answer that you’ve been
looking for.

Download Python
At this point, you are probably ready to get started with some of your own
coding with Python. You want to get the program downloaded so you can learn
how to make some of your own amazing codes. But before you can do this, you
need to make sure that all the right components are downloaded on your
computer. The good news is that since Python is compatible with all the
operating systems currently in use, you just need to start by turning on your
personal computer and then go to the next step.
Since this coding language is open sourced and completely free, all you have to
do is to visit the Python website, at www.python.com , to get started. There are a
few different versions to go with, so you should pick out the one that you think
you can use. There are versions available for each operating system so make sure
to look at this as well before choosing the version that you want to work with.
Once you decide on which version would work best for your computer, you just
need to click on the prompts that show up and do as instructed to get it
downloaded on your computer.
While you are waiting for the Python program to finish downloading, there are
also a few other tools that you will need that can help with writing these codes.
First, you have to make sure that you downloaded a text editor as well. This text
editor is the tool which you will use to write out the codes that you want to
make. You will also need an IDE or an ‘Integrated Development Environment’
which you can use to read and execute the codes that you want.
Let’s start with the text editor. It is not necessary that you go with a program that
is too complicated to make this work. The notepad text editor found on a
Windows computer or some other program will work just fine. There are a lot of
options that you can choose from here, but Notepad or something similar is free,
so it is a good option for you to work with.
Then you also need to take some time to work with the IDE. If you don't add this
to your computer, it will be impossible to write out or execute the code you want
to work on. There are a few different options when it comes to the IDE, so do
some shopping around to see which kind will offer all the features that you are
looking for. There is one IDE that is available, and you can get it through Python
so that you can keep things simple, but there are also other options available if
you need more choices.
Once you have downloaded the Python program as well as the IDE and the text
editor that you want to work with it is time to work on writing your own code.
The process is simple, but we do need to look at a few things first and learn
some of the basics so that you can start to write your own Python code in no
time.

The basics you should know about Python


As you get started with writing your own codes in this language, you will start to
see that there are many parts that come with them. Being able to understand how
these basic parts work will help you to write the codes that are needed in your
program. This section will quickly go over some of the basics that you need to
know before you start working with Python.

The keywords
First, we need to take a look at these important keywords in the Python
language. Similar to what you will find in other coding languages there is a list
of keywords in Python that are meant to tell your text editor what to do. These
keywords are reserved, and you should only use them for their intended purposes
if you want to avoid any issues with your code writing. They are basically the
commands that will tell your compiler how to behave, and they have to remain
in reserve so that you can execute the code without unnecessary issues
complicating the process.

How to name the identifiers


Once you are ready to write your own codes in Python, there are a few parts of
the code you will encounter, and they are called ‘identifiers.’ These ‘identifiers’
go by a lot of different names so it can get a bit confusing, but they will help by
getting your code to run the way you want it. You will notice that some of the
names that we used throughout this guidebook for identifiers include functions,
classes, variables, and entities. There are some rules to follow when naming your
identifier but these rules will be the same no matter what type of identifier you
are currently working with. Some of the rules that you should know about
include:
Naming these identifiers is simple. You can use both the lower-case
and the upper-case letters any time that you would like. Numbers
and the underscore symbol are allowed as well. Any combination of
the above are allowed, just make sure that you aren’t adding in
spaces in this name. So, you would name it ‘MyPythonProgram’
rather than My Python Program.
The identifiers can't start with any numbers. It is fine to use
numbers throughout the name, but you should never have this at the
beginning of the name or in the first character at least. This will
result in an error when you type it into the compiler so if you are
uncertain about why you see an error, be sure to double-check if this
is the reason.
The identifier shouldn’t have one of the keywords that we talked
about before. Doing this will confuse your compiler so just avoid it
completely.

As you can see these rules are not too complicated to keep in mind and outside
of them, you can name your identifiers whatever you would like. Now, if you are
working on the code and you forget one of the rules and give your identifier a
name that is not allowed then the compiler will provide you with a syntax error
which indicates that you need to go and fix it.

Statements
You will use a lot of ‘statements’ when writing out a code in Python. These are
useful for your code because they are just strings of code, these include some of
the other parts we have talked about, that you will send over to the compiler to
execute. You can write out pretty much any type of statement that you would
like in your code, as long as it is written out in a way that your compiler is going
to understand. You can choose to make a statement short, such as having a few
lines with it, or make it longer, there really aren't many rules that dictate how
you should do it.

Comments
The next component that you will use quite a bit in making your own code is the
‘comments.’ These comments are helpful because if someone else is taking a
look through the code that you wrote and they need some clarification on what
exactly it is you are talking about. You can write out the comments so that others
who want to read through or use the code will know what is going on. They are
basically little notes inside the code that help you and other programmers to
know what is happening during the application.
It is pretty easy to write out the comments that you want to add to your code.
You simply need to use the (#) sign in front of the comment that you want to
write. So, you could write out something like #this is my Python code. When the
comment is done, you just hit return and start writing the rest of the code on the
next line. As long as you have that sign right in front of the comment, then your
compiler can just skip over it and will not read out what you put in the comment.
You have the freedom to choose how many comments you would like to leave
inside of your code. Sometimes the code will just need a few of them while other
times the code may need a lot of comments. Keep the comments down to the
ones that you really need and do not waste time or space writing out more
comments than needed.

Functions
‘Functions’ are another important part of the Python programming language.
This is basically a part of the code that you can reuse, and it is often used to
finish off one action in the code. Functions are great because they are more
effective than other options, which means you can work on your code without
wasting a lot of time. There are a lot of functions that are found in the Python
language so you can benefit from this, plus, you are able to write out some of
your own functions as well.
While you are working on your code, you have to make sure that you are
defining the function. Once you are able to define the function and it is
considered finalized, it is time to execute it to work in the code. You have the
choice to call it up from the Python prompt, or you can call it up from another
function. Below is an example to show you exactly how you can do this:
#!/usr/bin/python
# Function definition is here
def print( str ):
"This prints a passed string into this function"
print str
return;

# Now you can call printme function


printme("I'm first call to user defined function!")
printme("Again second call to the same function")
When this is placed into your compiler, you will see the two statements that we
wrote out inside of the code that will come up just like a message. This is just
one example of how you would call up a function, and you can always change
up the statements that are inside the code to figure out how you want to execute
them later.

Working with variables


And finally, it is important that you spend some time to focus on variables.
Variables are important because they will save up spots on your computer's
memory to hold onto parts of your code. When you go through the process of
creating a new variable, in effect, you are making sure that some of the space on
your computer will be reserved. In some cases, such as when you are working
with data types, your interpreter will do the work of deciding where this
information should be stored and this helps speed up the process.
When it comes to working with variables, your job is to simply make sure that
the right variables are lining up with the right values. This will ensure that the
right parts show up in your code at the right time. The good news is that you are
able to give the variable any value that you would like, but do check if it actually
works inside of your code first. When you are ready to assign a new value to a
variable, you can use the equal sign to make this happen. Let’s look at a good
example of how exactly this would work:
#!/usr/bin/python

counter = 100 # An integer assignment


miles = 1000.0 # A floating point
name = "John" # A string

print counter
print miles
print name
With the above example, you will get the results to show up with the variable
that you placed with the value. So, when the counter shows up, it will show you
a 100 for the counter, 1000 for the miles, and John as the result of the name.
As you can see, there are a lot of different parts that can come with your Python
code. But all of these come together pretty well so that you can make some
complex and useful programs. You will use these quite a bit as you start to work
on more of your own codes.
Chapter 2

Classes and Objects

Now that we know a little bit more about the basics that come with the Python
code, it is time to move on to our first topic of working with classes and objects.
These two topics are important because they will make sure that everything in
your code stays in the right place. Your objects are the components which will
help define certain parts of the code so that they are organized and easier to
understand. The objects all share something in common, and they will be placed
into the same class, helping your code to work the way that it should.
There are a lot of things to understand when it comes to working with objects,
but the most important part is that whenever you place some objects into the
same class, they should have something in common. You can place anything in
the same class, but the best way to do this is to place ones that are similar
together in the same class. It adds in a little more order to the whole thing. Think
about this process as you organizing the closet. You have to make sure that your
closet is organized by placing the shoes in one area, hanging up the clothes in
another, adding the purses together, and then having a place for all those extra
things lying around. You do this process task it ensures that everything looks
nice and is easier to find later on.
This is the same idea when you are working on classes. You want to place the
similar objects into the same class so that it is easier to find them later on. The
program will work more efficiently when these objects are similar, rather than
randomly placing unrelated objects into the same class.
To make things easier to understand, you should see objects as different aspects
and parts of the code that you are writing and then the classes will be like the
containers which you will use to store away these objects. You can easily create
a class out of anything that you want and then add in similar objects that match
up together into that class. You can pick out whatever label that you want to go
with the class, just be certain that it actually makes sense for the type of object
that you want to place inside the class. When someone looks at the class, they
should have a good idea of what you placed inside of it and the objects should all
match that label as well.
If this is a new idea to you and you are just getting started with learning a new
coding language, objects and classes are a good place to start because they will
help you to learn more while also making sure that everything will stay
organized in the code that you are working on. As a programmer, it is your job to
learn how to create these classes and then get the objects to go inside of them so
that the code works the proper way. Let's take a look at how that is going to work
in Python.

How to create a new class


Now that we had a little introduction to these objects and classes, it is time for
you to learn the steps on how to create your own class. You have to do this
because you will find that it is hard to get started with anything in Python if
don’t do this first. Once you are ready to create the statements that are needed
for these classes, you should create a new definition.
You need to place the right keyword first to get this going and then add the name
of the class (the name that you are giving to it) right afterward. This will then be
followed with a ‘superclass’ that you will place inside of parenthesis. Another
thing that you should consider is that at the end of your first line in Python, you
need to add a semicolon. Your code will work without it, but this is considered a
part of coding etiquette, so you have to make sure that it is present.
The easiest way to understand how all these works is to take a look at an
example of creating a new class. A good example which will show you how to
do this with the Python language is shown below:
class Vehicle(object):
#constructor
def_init_(self, steering, wheels, clutch, breaks, gears):
self._steering = steering
self._wheels = wheels
self._clutch = clutch
self._breaks =breaks
self._gears = gears
#destructor
def_del_(self):
print(“This is destructor….”)
#member functions or methods
def Display_Vehicle(self):
print(‘Steering:’ , self._steering)
print(‘Wheels:’, self._wheels)
print(‘Clutch:’, self._clutch)
print(‘Breaks:’, self._breaks)
print(‘Gears:’, self._gears)
#instantiate a vehicle option
myGenericVehicle = Vehicle(‘Power Steering’, 4, ‘Super Clutch’, ‘Disk
Breaks’, 5)

myGenericVehicle.Display_Vehicle()
Before we move on, take the time to open up your text editor and write this code
down so you won’t forget it. As you work on writing this out, you should notice
that there are a few of the basics that we discussed and explained earlier that will
show up in this code. You will also see the definition of the object and the
method, the destructor function, the different attributes that you will need, and
also some regular functions. Since this is the first code that we will have a look
at, let’s break it down a bit so that you are able to understand and know how to
write out codes in this language better.

Class definition
The first thing we will talk about is the class definition. This is where you need
to write out the object instantiation and then the class definition so that your
syntax is proper when put inside the code. These are important because they are
the part of the code that will tell your compiler what it should do and which
commands are important. If you want to invoke the new class definition inside of
the code, you just have to use the ‘object.attribute’ or the ‘object.method()’
function and it will work flawlessly.

Special attributes
The next thing that you can focus on in the above code is the special attributes
that you want the code to recognize for you. You may want to take a closer look
at these because they will add a lot to your code and will help make it work
better. These special attributes will give you some peace of mind because you
can know when the attribute will be seen and you can make sure that it is used in
the right way to prevent the code from getting messed up. There are a lot of good
attributes that can be used in Python, but some of the ones that you really should
pay attention to as a beginner include:
__bases__

This is considered a tuple that contains any of the superclasses


__module__

This is where you are going to find the name of the module, and it will also hold
your classes.
__name__

This will hold on to the class name.


__doc__

This is where you are going to find the reference string inside the document for
your class.
__dict__

This is going to be the variable for the dict. Inside the class name.

How to access members of a class


Now we need to look at how you are able to access members of a class. To make
sure that your text editor and compiler are able to recognize a class and execute
the parts that you want, you must make sure that this code is properly set up to
access all the members of that class. You will be happy to know that there are a
few options you can use to make this happen, and all of them will work out well,
but the ‘accessor’ method is the most popular and the most efficient one to work
with.
To help you understand how this works, let’s take a look at the following code to
make it easier.
class Cat(object)
itsAge = None
itsWeight = None
itsName = None
#set accessor function use to assign values to the fields or
member vars
def setItsAge(self, itsAge):
self.itsAge = itsAge

def setItsWeight(self, itsWeight):


self.itsWeight = itsWeight

def setItsName(self, itsName):


self.itsName =itsName

#get accessor function use to return the values from a field


def getItsAge(self):
return self.itsAge
def getItsWeight(self):
return self.itsWeight

def getItsName(self):
return self.itsName

objFrisky = Cat()
objFrisky.setItsAge(5)
objFrisky.setItsWeight(10)
objFrisky.setItsName(“Frisky”)
print(“Cats Name is:”, objFrisky.getItsname())
print(“Its age is:”, objFrisky.getItsAge())
print(“Its weight is:”, objFrisky.getItsName())
Make sure to open up and place this in your compiler before we move on. If you
ask the compiler to run this, you should get some results that show up right
away. The results that you get will include that the name of the cat is Frisky (or
whatever name you would like to add in there) and that the age is five while the
weight is 10. This is the information that we placed into the code, but you can
add different names and different numbers in there if that works out better for
you. Try out a few different options to see what will work and learn how you are
able to make it work for you.
As you can see, classes and objects are really easy to work with. These are some
of the best ways you can use to take care of the information that is inside of your
code. You can create the class and then add the objects that you want and then
match it into the class that you created. This will keep your coding nice and
organized just like the way that you want it, and it also makes sure the program
will actually work.
Chapter 3

Conditional Statements in Python

Another important thing that you can learn about in Python is the ‘decision
control’ statements. These go by a few different names such as ‘conditional’
statements and the ‘if’ statements and they will do a lot to help you make the
code that you’re planning to create. In some cases, you might write out a code
that needs to make some decisions without your manual input. You can also add
in some conditions that should be met, and the computer program would then
have the ability to make the needed decisions. For example, if you are working
on a game and the user needs to pick from a few different options, you will be
able to tell the program how to act and respond accordingly in each situation.
Now there are a few if statements that you will be able to choose from. With the
basic one, you will basically have the program react only when the user puts in
the right answer. So, if you want the person to put in an age that is above 18, and
they put in one of those ages, then the program would continue on as you set it
up. But with this basic, if statement, if they pick an age that is lower than 18, the
program would see this as incorrect information and would close itself. Of
course, you can imagine a lot of times when this is not the best for your program,
but there are some other if statements that you can work with as well to help deal
with this issue.
So, let’s get started with working on these ‘if’ statements. We are going to take a
look at the most basic form, and then we will work our way up from there. This
is the easiest method to help you get a feel for how these ‘if’ statements are
supposed to work. With this option, your program is only going to proceed if the
user puts in the right answer and the program will refuse to proceed if you put in
the wrong answer. There are a few limitations to putting this one to use, but it is
better to get started one way or another, and this can be used as a foundation. A
simple example of how this will work is the following:
age = int(input(“Enter your age:”))
if (age <=18):
print(“You are not eligible for voting, try next election!”)
print(“Program ends”)
Let's look at how this code is working. There are a couple of things that you
should see happening with this code. If the user is in our program and they state
that they are 18 years old or younger, the program will continue to work as a
result. Those people who don’t enter the correct information will, for example,
see this message instead: "You are not eligible for voting, try next election!"
When the user sees this message appear on the screen, this will be the end of the
small program that we just wrote, but you can certainly add some more to it later
on. With this code, if the user ends up putting in an age that is over 18, the
program is not going to provide them with a result. Their age is not wrong, but it
doesn't match the conditions that you set, so it doesn't have anything to send over
at this point.
With this particular program, if the user tells the computer that they are 25 years
old, the program is set up to tell that this age does not meet the conditions that
you set. Because the conditions have not been met at this point, the ‘if’ statement
that we used is going to end the program right now. This can have some
limitations because you do not want the code to just randomly stop right here,
but that is what will happen based on what was placed in your code.
As we have mentioned, there will be times that you just want the code to respond
no matter what answer the user provides. You want the user to put in that they
are 25 or some other age without having the program shut down on them. The
first statements that we looked at were the ‘if’ statements, but to get the program
to respond regardless of what kind answer is put in, you will want to work with
the ‘if else’ statements.
With the ‘if else’ statement, it will not matter what the user puts into the
program. If the conditions you set out are not met, the program will simply move
on to the second part and decide to implement what you placed in there. Let’s
take a quick look at how this will work:
age = int(input(“Enter your age:”))
if (age <=18):
print(“You are not eligible for voting, try next election!”)
else
print(“Congratulations! You are eligible to vote. Check out
your local polling station to find out more information!)
print(“Program ends”)
As you can imagine, this is an option that will open up a lot more possibilities to
what you can do compared to the ‘if’ statement that we worked on before. You
will have two options that you can use with this one so that something will
always show up on the screen. Later we will even learn how to take more than
two answers to make the program work.
With the additional option that comes up, the user will be able to put in any age
that you will like. If the user types in that they are 17, for example, the statement
about them being too young to vote will show up on the screen. But if they put in
an age that is over 18, they will get the second statement to show up instead.
You will find that there is a lot more freedom to creating a useful code when you
work with the ‘if else’ statements. You are able to add in three, four, and even
more options so that a specific message will show up based on how you want
your code to work. The 'if else' statements can be used to make it easier for you
to get the program to react and to what your user is doing, no matter which
answers they decide to place inside.
Now, the example above of the if…else statements is pretty simple, and it is
possible for you to go through and add in more steps to the code as well. For
example, if you want to allow the user to put in more than two answers, such as
three or four options, you can do this just by adding in more parts to the code.
You could choose to have a different message come up for those who are in the
16 to 18 age group, one that is for those who are 19 to 25 years old, and another
for those who are at least 26 years old. There are a lot of possibilities and
methods that you can use, you just need to look at the program that you want to
work with and then split it all up based on what will work the best for your
code.

How to work with ‘elif’ statements


There is a third ‘if’ statement that you could work with as well. This one is
known as the 'elif' statement. We spent some time earlier in this guidebook
looking at the basics of the ‘if’ statements and how they are different compared
to the ‘if else’ statements. Both of these are great for adding in a sense of
interaction to your code. These allow the user to pick out from some options or
to add in their own information and the code will be able to interact with the user
without trouble. The elif statements can help take this to the next level to deliver
great results.
The elif statements are simple enough to use and easy to learn. Not to mention,
you can also add in more of these statements to your code as much as you would
like. The example that we will show in a bit will give the user three different
options to choose from as well as a catch-all that the user can go with if they are
not happy with any of the other answers. This is just to keep things simple. You
can add as many of these ‘elif’ statements as you would like which also means
you can add in as many of these statements as you need to make the code work.
That is one of the great things about working with the elif statements; it gives
you a lot of freedom to make sure the code works for you. Now that you know a
little bit more about what the elif statement is all about, it is time to take a look
at an example so that you can see this one working. Remember that the option
below is just a simple elif statement and you can certainly add more to it to get
the results that you want from the code.
Print(“Let’s enjoy a Pizza! Ok, let’s go inside Pizzahut!”)
print(“Waiter, Please select Pizza of your choice from the menu”)
pizzachoice = int(input(“Please enter your choice of Pizza:”))
if pizzachoice == 1:
print(‘I want to enjoy a pizza napoletana’)
elif pizzachoice == 2:
print(‘I want to enjoy a pizza rustica’)
elif pizzachoice == 3:
print(‘I want to enjoy a pizza capricciosa’)
else:
print(“Sorry, I do not want any of the listed pizza’s, please
bring a Coca Cola for me.”)
When you place this into your compiler, it is going to come up on the screen so
that the user is able to choose from the choices that you have listed. The user can
easily pick out the number that goes with the pizza of their choice. There is also
an option for you to go with in case the user doesn't want any of the pizzas and
they would like to get a drink instead. This is known as the ‘elif’ statement and is
meant to catch on to all of the options that the user wants but are not listed
above.
And that is how the ‘if’ statements work. You can set up the conditions that you
want to work with so that the program behaves exactly as planned. You can
make it so that there is only one right answer, make it so that the user is able to
input any answer that they want and a variety of answers will show up, or you
can make a menu list so that the user can pick any item what they want. This
allows the user to have a ton of interaction with your program.
Chapter 4

Inheritances to Clean Up the Code

The next topic that we will take a look at when writing Python codes is how to
work on inheritance codes. These 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. Let’s take a look at what
the inheritance code looks like and how it will work inside of your code:
#Example of inheritance
#base class
class Student(object):
def__init__(self, name, rollno):
self.name = name
self.rollno = rollno
#Graduate class inherits or derived from Student class
class GraduateStudent(Student):
def__init__(self, name, rollno, graduate):
Student__init__(self, name, rollno)
self.graduate = graduate

def DisplayGraduateStudent(self):
print”Student Name:”, self.name)
print(“Student Rollno:”, self.rollno)
print(“Study Group:”, self.graduate)

#Post Graduate class inherits from Student class


class PostGraduate(Student):
def__init__(self, name, rollno, postgrad):
Student__init__(self, name, rollno)
self.postgrad = postgrad

def DisplayPostGraduateStudent(self):
print(“Student Name:”, self.name)
print(“Student Rollno:”, self.rollno)
print(“Study Group:”, self.postgrad)

#instantiate from Graduate and PostGraduate classes


objGradStudent = GraduateStudent(“Mainu”, 1, “MS-
Mathematics”)
objPostGradStudent = PostGraduate(“Shainu”, 2, “MS-
CS”)
objPostGradStudent.DisplayPostGraduateStudent()

When you type this into your interpreter, you will get the following
results:
(‘Student Name:’, ‘Mainu’)
(‘Student Rollno:’, 1)
(‘Student Group:’, ‘MSC-Mathematics’)
(‘Student Name:’, ‘Shainu’)
(‘Student Rollno:’, 2)
(‘Student Group:’, ‘MSC-CS’)

How to override the base class


The next thing that we can work on when it comes to inheritance codes is how to
override a base class. There will be a lot of times that while you are working on
a derived class, you have to go in and override what you have placed inside a
base class. What this means is that you will take a look at what was placed inside
the base class and then make changes to alter some of the behavior that was
programmed inside of it. This helps to bring in new behavior which will then be
available inside the child class that you plan to create from that base class.
This does sound a little bit complicated to work with, but it can really be useful
because you can choose and pick the parental features that you would like to
place inside the derived class, which ones you would like to keep around, and
which ones you no longer want to use. This whole process will make it easier for
you to make some changes to the new class and keep the original parts from
your base class that might help you out later. It is a simple process that you can
use to make some changes in the code and get rid of parts of the base class that is
no longer working and replaces them with something that will work better.

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 5

How to Work with


Exceptions in the Code

Now it is time to take a look at how you would work on exceptions inside of
your Python code. As you work with some new codes in Python, there will be
some times when adding in an exception can be helpful. In coding, these
exceptions are a bit more complicated, but it is important that you learn exactly
how you can work with them so that your code will behave the way that you
want it. Some of these exceptions can be found in the Python library and this
something that’s raised automatically by the program. Then there are the
exceptions that will be raised by you because that is how you want your program
to work. Let’s take a look at how to work with exception handling so that you
can get the program to work exactly the way that you want it.
As you are working on your code, if an abnormal condition happens inside the
code, either one that the Python language is going to recognize or one that you
set up for your particular code, you need to pay attention to see if there is an
exception that shows up for the code.
As we have briefly mentioned, there are going to be a few exception conditions
that the compiler will already recognize, and if they are used, the code won't
allow the program to finish. For example, if you are adding in the wrong kind of
statement to the code, or if you misspell one of your classes so the compiler can't
find it, or you try to divide by zero, the compiler won't be able to deal with this
request and the exception will be raised by the program.
These are just a few examples of the types of exceptions that the compiler will
raise for you. In addition to that, there are times when you might want to change
the program that you are currently working on, and you want it to raise an
exception. These kinds of exceptions are technically just fine with the
interpreter, but according to what you want the program to finish, you want the
code to raise these exceptions.
So, you may be wondering exactly how this is all going to work. A good
example of this is when you want to set up a website that is targeted at and
limited primarily to an adult audience. You want to make sure that every user
who tries to get on is no younger than 21 years old. At the same time, your
program must also have the ability to raise an exception which will show up on
the screen if your user happens to say that they are less than 21 years old. When
this does happen, you can then make sure that the code raises that exception and
that the user is not able to continue on and access that website.
One thing you should work on or look through as you are working on your
program is the library that was provided along with Python. You will notice that
this library contains a list of some of the exceptions that are recognized
automatically by the compiler. It will help if you know and remember what they
are because they can help make your code writing so much more efficient and it
will also help you understand so you can know why the program is acting in a
certain way.
One common exception that you will find when using Python is if you try to
divide by zero. If you or a user tries to do this, an error message will show up to
inform you. In addition, you may experience some issues with these exceptions
when you try to read to a point in the file that is past where the current file is
actually located. Both of these actions will bring up an exception and create an
error in your code.
Now it is a good idea to know some of the exceptions that are found in your
Python library so you can work with these as you go through and work on your
code. Some of the different exceptions that you may encounter when working
with exceptions include:
Finally
This is the action that you can use to perform cleanup actions, whether the
exceptions occur or not.
Assert
This condition will trigger the exception inside of the code.
Raise
The raise command can trigger an exception manually inside of the code.
Try/except
This is when you want to try out a block of code and then it is recovered thanks
to the exceptions that either you or the Python code raised.

How to raise an exception


We have spent a good amount of time talking about these exceptions and what
they are about, but now it is time for you to take a look at how you will use these
inside the code that you want to write. If you are working on your code and you
see that there is some kind of issue that is showing up or you would like to see
why your program is doing something that seems wrong, the compiler will go
through it, and it will raise up a new exception. This is because the program
looked through the code as well and is having some trouble figuring out exactly
what you would like it to do.
Often the issue that you’ll encounter is simple enough you can fix it yourself,
such as when you try to bring up a file, but you type in the name wrong. Or it
could be something like when you or the user tries to get the program to divide
by zero.
A good way to understand how these exceptions are going to work is to take a
look at an example and get the compiler to raise an exception against what you
want to get done inside the code. The following is a good example:
x = 10
y = 10
result = x/y #trying to divide by zero
print(result)
The output that you will get when you try to have the interpreter executethis
code would be:
>>>
Traceback (most recent call last):
File “D: \Python34\tt.py”, line 3, in <module>
result = x/y
ZeroDivisionError: division by zero
>>>
With the example that we talked about above, the program will show an error as
a result because in this code you are trying to divide by zero, and this is not
something that the Python code would allow you to do. Now, if you really do
want to try and get through so you can run the program the way that it is, you
may not want that messy error message to show up. This will not make your
code look professional, and the user won’t really understand what that error
message entails. The good news is that you can make some necessary changes
here so that the message looks a bit different.
There are a few different options available that you can work with which will
help to add this new change to the code while at the same time allowing you to
choose what will happen if an exception is raised. You do not want to get that
ugly exception message above, but you can easily go through and change it so
that the message will say something that is a lot nicer or at least explains what
exactly is going on with the error.
A good example of the code that you want to write to make this work for you is
the following:
x = 10
y = 0
result = 0
try:
result = x/y
print(result)
except ZeroDivisionError:
print(“You are trying to divide by zero.”)
Now, the code that we just wrote looks pretty similar to the one that we wrote
above, but it will change the message that appears when the user raises the
exception. With this code, the ugly error message has been erased and was
replaced with the much more understandable error message: ‘You are trying to
divide by zero’ that will show up on the screen. You can make just about any
kind of change that you want to the message, and this will provide you with a
good place to start with the syntax.

How to define your own exceptions


So far, we have just gone through and took a look at how you can handle
exceptions if these are the exceptions that the program recognizes. But there will
still be times when you want to raise some of your own exceptions. For example,
you could work on code, and you want to make sure that your users can only
access and use certain numbers while the rest will not be accepted. This could
work well if you’re planning to create a game where you want to raise an
exception that if the user tries to guess too many times than what is allowed, they
will be limited. Once the user has exceeded the limit of how many guesses
you’ve allowed them to make (a limit of two or three times for example), the
compiler can be programmed to raise an exception which will tell the user they
are not allowed to guess again since they’ve used up the number of guesses they
can make.
The compiler is not going to recognize that there is anything wrong with how
many times the user guesses. As far as the compiler is concerned, the user can
guess an unlimited amount of times. But when it comes to a game or another
program that you are creating, you do not want the user to get stuck and never be
able to progress which is why you have to set an exception for how many times
they can make a guess.
These exceptions are unique to your code, and without you writing them into the
code as exceptions, the compiler would never recognize them as such. You can
add any kind of exception that you would like and you can add a message as
well, similar to what we did above. The code that you can use to make this
happen looks like the following:
class CustomException(Exception):
def_init_(self, value):
self.parameter = value
def_str_(self):
return repr(self.parameter)
try:
raise CustomException(“This is a CustomError!”)
except CustomException as ex:
print(“Caught:”, ex.parameter )
In this code, you have been successful in setting up your own exceptions and
whenever the user raises one of these exceptions, the message of ‘Caught: This
is a CustomError!’ is going to come up on the screen. This is the best way to
show your users that you have added in a customized exception into the
program, especially if this is just one that you personally created for this part of
the code, and not one that the compiler will recognize on its own.
Just like with the other examples that we discussed, we worked with some
generic wording so we can show exactly how exceptions are supposed to work.
You can easily go and change this whenever needed so you can get a message
which is unique for the code that you are writing and can explain to the user
exactly what just happened if the error message shows up on their screen.
Exception handling is something that you will work with a lot more as you start
to write out some more advanced codes on Python. There are a lot of times when
you will work with either the exceptions that are recognized by the program or
ones that you want to bring up for the code that you are writing in particular.
Working with some of the codes that we bring up in this chapter will help you to
deal with these exceptions, and it can also make sure that you can make them
look good for the user. Make sure to try writing a few of these codes in your
compiler to get some practice with these exceptions so you can get a good idea
of basically how these exceptions are supposed to work.
Chapter 6

The Value of Loops

Now it is time to take a look at how you can go about writing out loops inside of
your code. Earlier we talked about the conditional statements and how you can
use these to help the program interact with your user a bit more. But there are a
couple limitations that we haven’t talked about yet when it comes to the ‘if’
statements and this is where using the loops can help you out. These loops are
very useful because every time you work on a program that you would like to
repeat itself inside the code, you do not want to spend all that time rewriting the
same line of code over and over again. That’s just exhausting.
Let’s say that you want to get the code to list out all the numbers from one to ten.
You do not want to go through and write out all of this over and over again. It
takes up too much time and will make your code look really messy. But with the
help of the loops, you can get this exact same task done with just a line or two of
coding to help you out.
There is a lot of information that you are able to put inside of a loop, and they
are still really easy to work with regardless. These loops are capable of telling
your compiler that it needs to read through the same line of code over again until
the conditions that you set have been met. If you are asking the compiler to write
out all the numbers from one to ten, you will just tell the code to keep counting
up until it reaches ten. This is easy to accomplish, and with a loop, you can do it
with just a few lines of simple code.
When you are working with loops, it is important to remember that you need to
set up the condition before you decide to run the program. If you do not set the
conditions or if you forget, then you will end up placing your code into a
continuous loop that will freeze and crash the computer. Always double check
the parts of the codes where you used loops to write it so you can make sure that
you have set these conditions ahead of time.
As you are working on your Python code, you may eventually discover that
when it comes to the loops, you can use you are not limited to one kind because
you have a wide array of available options to choose from. We are going to talk
about some of the most common types of loops that you can choose from and
explain when you would want to use each one.

The ‘while’ loop


There are different kinds of loops that you can work with, but the first one that
we will have a look at is known as the ‘while’ loop. This loop is one you can
work with anytime if you’re sure about how often you want the code to go
through the cycles. So, if you want the code to do a few rounds before it moves
on to another part, then going with the while loop is the best choice for you. If
you want to make sure that it doesn’t go through this cycle an indefinite amount
of times, then you must make sure that you write down some conditions into the
code at the beginning to avoid this problem.
The while loop is the best option for you to choose if you like to make sure that
the program goes through the loop at least one time to see if the results are true
or false. To see how the while loop works, let’s look at the example of this loop
below:
#calculation of simple interest. Ask user to input principal, rate of
interest, number of years.
counter = 1
while(counter <= 3):
principal = int(input(“Enter the principal amount:”))
numberofyeras = int(input(“Enter the number of years:”))
rateofinterest = float(input(“Enter the rate of interest:”))
simpleinterest = principal * numberofyears *
rateofinterest/100
print(“Simple interest = %.2f” %simpleinterest)
#increase the counter by 1
counter = counter + 1
print(“You have calculated simple interest for 3 time!”)
Before we move on, open up your compiler and type all of this in so that the
code can be executed. Once you have completed this task, you will notice that
the resulting output will allow the user to place whatever information that they
want inside of it and they can get the program to compute that information. As
an example, let’s say the user is trying to do something which involves interest
rates, and the user wants to add those numbers to the program to see what will
happen. We set it all up so that the loop will decide to go through the motions a
minimum of three times with the help of the user, but you can make changes so
that it goes through as many times as you would like.

The ‘for’ loop


Another type of loop that you may want to work with is the 'for loop.' When you
are working with the for loop, you will see that it is different compared to the
while loop, but it is useful for many of the codes that you might try to write. In
fact, you will find that the for loop is the traditional way to write out the loops,
so it is definitely worth your time to learn how to use it.
Once you are ready to work with the for loops, you will find that the user will
not have access to go into their code and enter the information they want it and
use it to get the loops to start. But, with this loop, Python is can through the
iteration in the order that it shows up in the statement and this is what will show
up on the screen. It won’t require input from the other person, and it will just go
through the entire iteration until it reaches the end. A good example of how this
works is with the following code:
# Measure some strings:
words = [‘apple’, ‘mango’, ‘banana’, ‘orange’]
for w in words:
print(w, len(w))
When we take a look at the example above, you are able to place the information
that you want inside of this code, and then when it has the time to execute, the
program will take some time to list out the fruits that we have inside. These are
going to be listed in the same order that you placed them in the code. If you
would like them to show up in a different order, then you will need to go through
and make these changes. This is not something that you are able to change once
the code is executing.

The ‘nested’ loop


The final kind of loop that we will have a look at inside this guidebook can be
really helpful with the code that you want to write, and it is known as the
‘nested’ loop. Any time that you decide to work with a nested loop, you can take
the basic loops that we learned about earlier and then place it inside of another
loop. Both of these loops can work at the same time, and they will continue on
and on until they are complete. There are many situations where this loop can be
applied to benefit your code, such as when your code is trying to write out its
own multiplication table. Let's take a look at an example to see how you can
write out this kind of nested loop.
#write a multiplication table from 1 to 10
For x in xrange(1, 11):
For y in xrange(1, 11):
Print ‘%d = %d’ % (x, y, x*x)
When you got the output of this program, it is going to look similar to this:
1*1 = 1
1*2 = 2
1*3 = 3
1*4 = 4
All the way up to 1*10 = 2
Then it would move on to do the table by twos such as this:
2*1 =2
2*2 = 4
And so on until you end up with 10*10 = 100 as your final spot in the sequence
These are the three most basic types of loops that you can work with and will
help you immensely to write useful codes and create great programs using the
Python programming language. You can use these loops to help you to clean up
your code a little bit so you can make sure that the same part of code rewrites
itself as well as ensure that your code is working exactly the way that you want
it. It is much easier to work with compared to the if statements when you get the
same task of having things repeat over and over again in the code. Your code
will look better, and there are countless functions it can fulfill when you decide
to add in a loop to the code.
Conclusion
Thank you for making it through to the end of this book, let’s hope it was
informative and that it was able to provide you with all of the tools you need to
achieve your goals whatever they may be.
The next step is to download the things that you need to get started with Python
so that you can work on some of your own codes. Python is a great programming
language to learn because it is simple enough for a beginner to use but it still has
all the functionalities that you need to make a useful and unique code. This
guidebook will provide you with all the answers that you need so you can get
started on making your own Python codes. Once you are ready to start learning
how to write your own codes, there is nothing better than learning how to use
Python, and this guidebook will help you to get started today!
Finally, if you found this book useful in any way, a review on Amazon is always
appreciated!
SQL

The Ultimate Beginner's Guide


to Learn and Understand SQL
Programming Effectively
Introduction
The following chapters will discuss everything that you need to know to get
started with the SQL language. If you run your own business, you know how
important having a good database in place can be for the good of your company
and for the products that you are trying to sell. And when it comes to databases,
you will find that none will work better than the SQL language.
This guidebook will take some time to explore the SQL language and how you
can use it to take your database to the next level. In this guidebook, we will take
a look at some of the basics of databases and the SQL language. We will then
move on to some of the different things that you can add to this database
including the commands to make it work, how to work with data types, and even
how to do a search or create some new tables.
Once you are done with this guidebook, you can do many of the important tasks
that you need to do to make SQL work for you. It is so important to have a good
database in place if you want to properly serve your customers and keep your
information in order and the SQL language will make sure that you are actually
able to do this.
When you are ready to learn more about the SQL language and how it will work
for all your needs with a database, make sure to check out this guidebook so you
can learn how to get started today.
There are plenty of books on this subject on the market, so thanks again for
choosing this one! Every effort was made to ensure it is full of as much useful
information as possible, please enjoy!
Chapter 1

The Basics of SQL

If you are interested in learning a new coding language, there are a lot of
different options that you can choose from, and it really depends on what you are
looking for and what you want to do with them. Some of these languages are
good for helping you to create a good website. Some are better for beginners
while others are good for those who are more advanced. Some are good for
creating a smartphone application or for working on your own game to share
with others. And then you can also choose a coding language that is like SQL,
which are meant to help businesses stay organized and keep track of their
information without all the challenges that can come with this.
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.
What is SQL?
It is best to start at the beginning. SQL is a programming language that stands for
‘Structured Query Language,’ and it is a simple language to learn considering it
will allow interaction to occur between the different databases that are in the
same system. This database system first came out in the 70s, but when IBM
came out with its own prototype of this programming language, then it really
started to see a growth in popularity and the business world started to take
notice.
The version of SQL that was originally used by IBM, known back then as
ORACLE, was so successful that the team behind it eventually left IBM and
became its own company. ORACLE, thanks to how it can work with SQL, is still
one of the leaders in programming languages and it is always changing so that it
can keep up with everything that is needed in the programming and database
management world.
The SQL is a set of instructions that you can use to interact with your relational
database. While there are a lot of languages that you can use to do this, SQL is
the only language that most databases can understand. Whenever you are ready
to interact with one of these databases, the software can go in and translate the
commands that you are given, whether you are giving them in form entries or
mouse clicks. These will be translated into SQL statements that the database will
already be able to interpret.
There are three main components, and we will discuss these in more depth in the
next chapter. But these main ones will be ‘Data Control Language,’ ‘Data
Definition Language,’ and ‘Data Manipulation Language.’
If you have ever worked with a software program that is database driven, then it
is likely that you have used some form of SQL in the past. It is likely that you
didn't even know that you were doing this though. For example, there are a lot of
dynamic web pages that are database driven. These will take some user input
from the forms and clicks that you are making and then will use this information
to compose a SQL query. This query will then go through and retrieve the
information from the database to perform the action, such as switch over to a
new page.
To illustrate how this works, think about a simple online catalog that allows you
to search. The search page will often contain a form that will just have a text
box. You can enter the name of the item that you would like to search using the
form and then you would simply need to click on the search button. As soon as
you click on the search button, the web server will go through and search
through the database to find anything related to that search term. It will bring
those back to create a new web page that will go along with your specific
request.
For those who have not spent that much time at all learning a programming
language and who would not consider themselves programmers, the commands
that you would use in SQL are not too hard to learn. Commands in SQL are all
designed with a syntax that fits in with the English language. They will begin
with a command statement that is in charge of describing the action that the
program should take. They will then be followed by a clause that will describe
the target of the command. This can include a specific table within a database
affected by the command. And then it will all end with a series of clauses that
are responsible for providing some more information.
At first, this will seem really complicated, and you may be worried about how
much work it will be to get it set up. But when you start to work on a few codes,
you will find that it is not actually that hard to work with. Often, just reading out
the SQL statement will help you to figure out what the command will do. Take a
look at the code below:
DELETE
FROM students
WHERE graduation_year = 2014
Read that code out loud, and you can probably guess what will happen when you
decide to execute your code. Most of the codes that are presented in the SQL will
work like this, so you do not need to be an expert programmer to make the SQL
language work for you. Considering this is a language that allows the authorized
users to look through a database and find the information that they want, it
makes sense that the SQL language is really easy to use.
SQL may sound like it is a complicated language for you to learn, but it is
actually really easy to figure out. We will spend some time looking at all the
different things that you can do when you decide to use the SQL language to
help you control the database that you use in your company. It is made to be easy
and to make things easier when you are working with the database, or when you
are trying to make it easy on your user to find information and SQL certainly
delivers on this.
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. The user would be
able to get onto these computers and interact with the mainframe, which in this
case would be a ‘dumb’ terminal or one that is not able to interact all on its own.
If a user wanted to be able to get the information to show up the correct function,
the dumb terminal would need to rely on all the information that is inside the
computer, such as the memory, processor, and storage.
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.

How to work with databases that are online


There are a lot of business owners who will find that the client and server
technology is the one that works for them. This system is great for many
companies, but there are some things that you will need to add or take away at
times because of how technology has been changing lately. There are some
companies that like the idea that their database will do better with the internet so
that they can work on this database anywhere they are located, whether they are
at home or at the office. There are even times when a customer will have an
account with the company, and they will need to be able to access the database
online as well. For example, if you have an account with Amazon, you are a part
of their database, and you can gain access to certain parts through this.
As the trend continues for companies to move online, it is more common to see
that databases are moving online as well and that you must have a website and a
good web browser so that the customer can come in and check them out. You
can always add in usernames and passwords to make it more secure and to
ensure that only the right user can gain access to their information. This is a
great idea to help protect personal and payment information of your customers.
Most companies will require that their users pick out security credentials to get
on the account, but they will offer the account for free.
Of course, this is a system that is pretty easy to work with, but there will be a
number of things going on behind the scenes to make sure that the program will
work properly. The customer can simply go onto the system and check the
information with ease, but there will be a lot of work for the server to do to make
sure that the information is showing up on the screen in the right way, and to
ensure that the user will have a good experience and actually see their own
account information on the screen.
For example, you may be able to see that the web browser that you are using
uses SQL or a program that is similar to it, to figure out the user that your data is
hoping to see. The SQL system will be used to reach your database, as soon as
the customer can put in what they are looking for. The SQL system will see this
query, and then bring back information on the website that will show up on the
web browser, and if the system is working properly, the right information will
show up on the page.

Why is SQL so great?


Now that we have spent some time talking about the various types of database
management systems that you can work with, it is time to discuss why you
would want to choose SQL over some of the other options that are out there. You
not only have the option of working with other databases but also with other
coding languages, and there are benefits to choosing each one. So, why would
you want to work with SQL in particular? Some of the great benefits that you
can get from using SQL as your database management system includes:
Incredibly fast

If you would like to pick out a management system that can sort through the
information quickly and will get the results back in no time, then SQL is one of
the best programs to use for this. Just give it a try, and you will be surprised at
how much information you can get back, and how quickly it will come back to
you. In fact, out of all the options, this is the most efficient one that you can go
with.
Well defined standards

The database that comes with SQL is one that has been working well for a long
time. In addition, it has been able to develop some good standards that ensure the
database is strong and works the way that you want. Some of the other databases
that you may want to work with will miss out on these standards, and this can be
frustrating when you use them.
You do not need a lot of coding

If you are looking into the SQL database, you do not need to be an expert in
coding to get the work done. We will take a look at a few codes that can help,
but even a beginner will get these down and do well when working in SQL.
Keeps your stuff organized

When it comes to running your business, it is important that you can keep your
information safe and secure as well as organized. And while there are a ton of
great databases that you can go with, none will work as well as the SQL
language at getting this all done.
Object-oriented DBMS

The database of SQL relies on the DBMS system that we talked about earlier
because this will make it easier to find the information that you are searching for,
to store the right items, and do so much more within the database.
These are just a few of the benefits that you can get when you choose to work
with the SQL program. While some people do struggle with this interface in the
beginning, but overall there are a ton of good features to work on with SQL, and
you will really enjoy how fast and easy it is to work with this language and its
database.
Chapter 2

The Commands That


You Should Learn

Now that we have taken some time to learn what SQL is about as well as some
of the basics of the databases that business owners will use, it is time to get more
in-depth about this system. This chapter will take some time to learn some of the
commands that you would need to use to make sure that you get this system to
do what you would like.
If this sounds scary in the beginning, do not worry about it. This is an easy
language to learn, and the commands will be intuitive to work with. It is
nowhere near as complicated as some of the other coding languages that you
may want to work with. This chapter will help you out with these commands by
splitting them up into six categories so that you understand how each of them
works. The six categories of commands that you will use when working with
SQL include the following:

Data definition language


This category is known as the ‘DDL,’ and it is one of the aspects that you need
to learn about the inside of SQL. This is in charge of allowing you to generate
objects into the database before you arrange them in the way that will work the
best for you. For example, this is the aspect of the SQL system that you should
use any time that you would like to make some changes in your table, such as
adding or taking away objects. There are some commands that you can use that
can help you to see these changes. These include:
Create a table
Alter a table
Drop a table
Create index
Alter an index
Drop view
Drop index

Data manipulation language


The next thing that you can work with inside the SQL language is the data
manipulation language. This one is called ‘DML’ when working with SQL, and
it is the part that you can use when you are trying to modify the objects that are
inside of your database. This will make it easier for your user and yourself to
have some more freedom when you are looking through the information in your
database and allows you to add in something new that will help the database
work better.

Data query language


When you are working with the data query language or the ‘DQL,’ you will
work with what many experts believe is the most powerful aspect of what you
can do with the SQL system. If you would like to work with the DQL inside of
this program, there is only one command that you will need to make this work.
The command that you will need to use to make this work is ‘Select.’ This is an
easy command to work with that will offer you a variety of ways to do things
with it, including running queries while you are inside your relational database.
If you are interested in looking through some results that are more detailed, you
would need to make sure that you are working with this select command through
DQL.

Data control language


The data control language is another part of SQL that you should learn how to
use when you want to add some more power to the codes that you are writing.
This will work out well when you would like to have some more control over
who can get access to the database. If your company can deal with the personal
information of your customers, such as their credit card information, it is a good
idea to use the data control language so that you can place some limits on who
can use these databases and access the information.
The DCL command will be used to help generate the objects that you need to
control who to access the information in the database so that only the right
people can get into the database. You can control who can get onto the database,
who can distribute the information that is in the database and so much more.
Some of the commands that you would be able to use inside of the DCL include:
Revoke
Alter password
Grand
Create synonym

Data administration commands


When you are working with some commands that work well within the SQL
system, you are also able to find a few that can analyze and audit the operation
that is inside the database. There are also sometimes where you can access the
performance on the database overall with the help of these same commands. If
you would like to fix something that is not working the way that you would like
inside the database, or you would like to make sure that you get rid of the bugs
that will affect the system you can use these commands. While there are some
different options that you can go with, the two options that you are most likely to
work with are:
Start audit
Stop audit

One thing that you need to think about when you are working with the SQL
system is that the database administrator and the data administrator are two
different things when you are working in this system. So, the database
administrator is the part of the code that will manage all of the parts of your
database, such as the commands that you are setting up inside of SQL and these
commands will be more specific in the implementation that is done in SQL.

Transactional control commands


There are many times when you will want to manage and keep track of
transactions that are inside of your database. If you are trying to do this within
your database, you should use the transactional control commands to make it
work. If you are a company that has their own website to sell your product, you
will find that these commands will help you keep it all in line. There are more
than a few things that you can use these transactional control commands for
including:
Commit
This is the command that you can use when you are looking to save
information that will relate to the different transactions that show up in
the database.
Savepoint
You will want to use this command any time that you are looking to
generate different points inside the group of transactions. You will also
want to use this command at the same time as the rollback command
that we will talk about later.
Rollback command
The rollback command is the one that you will use when you want to
take a look through your database, and you want to see which one you
can undo inside.
Set transactions
This command is the one that you can use any time that you are trying to
take your transactions in the database and give them names. The set
transaction will be the one that you use if you would like to try to label
things for a bit more organization.
It is important to learn how to work with all six of these categories when you
want to work inside of SQL. They will help you to get more out of your searches
so that the database will provide you with the information that you are looking
for. We will take some time to explore these a bit more as we go through this
guidebook so you can use them a little bit better. Understanding some of the
basics that come with your SQL system will help you get the best results while
using this system.
Chapter 3

The Different Data


Types That Work in SQL

Now that we have taken the time to look at some of the commands that you will
want to use inside of the SQL language, it is time to take a look at some of the
data types that you can use to make this SQL language work well while you are
creating your new code. These data types will change based on what you would
like to have done inside that database as well as the different items that you
would like to offer or sell to your customers.
The various data types that are most commonly found inside of this SQL system
will be the attributes that will go with the information that is on the inside and
then these particular characteristics will be placed on a table that you can read
through and retrieve any time that you would want to have a look.
Let’s take a look at how this works. A good example is when you require that a
field that you want to work with is only able to hold only numeric values. You
will find that you can use SQL to set it all up so that the user will only be able to
place a number inside of that database, or at least in that particular cell of the
table. So, if you have a cell on the table where you only want them to be able to
place their phone number or their credit card number, you could add this on as a
restriction. By assigning the right types of data to the fields that you would like
to have come up inside the table, you are making sure that fewer errors come up
on the side of the customer.
One thing that you should think about when you are working with your SQL
system is that all the versions that you could work with will be a bit different and
you may have to add in some different choices when you are picking out the data
that you would like to use. You must check out the rules that come with the
version of the SQL you are using to make sure that all of it will stay in order. For
most cases, you can use the data points that are specific to the version that you
chose to make sure that the database is working the way that you would like.
There are some basic types of data that you can use when you are working with
SQL, no matter which version you are working with. Some of the data types that
you can use include:
Time and date values
Numeric strings
Character strings

Characters that are fixed in length


Now it is time to take a look at some of the types of data that you can work with
inside of SQL. The first one that you may want to use is the fixed length
character. If you want to work with constant characters or even strings that will
stay the same all the time, you will need to make sure that you get them saved in
the system the right way. The typical data type that you will want to work with
when picking out these characters is this sample:
CHARACTER(n)
Look carefully at the example above, the ‘n’ that we placed inside the
parenthesis is the maximum length or the assigned length that you will allow that
particular field to be. For example, you may use this for the phone number field.
You would want to just keep it at ten characters so that the customer will only
put a phone number and nothing else inside of it. You could also do this for some
of the other parts of the code, but you will need to be careful with this. For
example, if you put these restrictions on the name of the customer, they could
end up with some issues if their name is longer than the characters that you
allow.
Depending on the version of SQL, you may find that it will work with the
‘CHAR’ data type instead, to save information that you will need that is a fixed
length. It is a good idea to work with this kind of data type when you would like
to work with any information that is alphanumeric. So, if you would like to set
up a part that will allow the user to place in their name of their state, but you
would like to make sure that they use the abbreviation of the state rather than the
whole name, you would be able to use the character limit and set it at two so that
everyone knows how it should work.
When you are working with the character of the data type, your user will not be
adding in information that is longer than the character limit that you set. Let's
say that you live in South Dakota, but you would like to make sure that the user
can only put in the abbreviation you will need to set the character for two. If the
user tries to put in more than two characters at this point, it is not going to work
for them.
There are many times when you are working with your database where you
would want to add a limit to the characters that you and the user can use. But
when you are working with the password and the username that your user should
be allowed to work with, it is best to not use a fixed character length for these.
Let the user pick out what is best for this. Sometimes you may want to set a
minimum length to help with security but never set a maximum so that the user
has the freedom they need to create a good username and password.

Variable characters
It is also possible that you can work with variable characters rather than the fixed
length characters that we talked about above. Instead of telling the user how
many characters they are allowed to have, you can allow the user to pick out
how long this should be. This one is a good option when you are working with
fields such as the name (which can easily reach varying lengths depending on
the person) as well as with the usernames or the passwords that the user would
like to use to make them unique. If you have a field that you would like to use
this way, the notation that you would use includes is this:
CHARACTER VARYING (n)
With the option that we used above, you will see that the ‘n’ will be the number
that will identify the maximum or the assigned value. You will then be able to
pick out from more than a few different kinds that you would like to put in here
to work with your variable characters such as ANSI, VARCHAR, or
VARCHAR2.
For this particular data type, there is no requirement that you would have to meet
when it comes to filling out the spaces for your user. If you assigned a length
that was for 15 characters, the user would be able to add in some less if they
would like, and you would not have issues like you probably would with the
fixed length characters we talked about above.
Any time that you are interested in working with some character strings that may
be considered variables in your language, you should make sure that, as much as
you can, you are using varying data types. The reason for this is because it will
allow you to maximize the space that you can use in your database and will
make it easier for the user to input their information without confusing the
database in the process.

Numeric values
Now we will take a look at how these numeric values can work on your code
with SQL. It is possible to work with numeric values any time that you would
like when you are in the SQL system. These values are the ones that you will
store right in the field using a number rather than using a letter. These values will
go by some different names depending on which numeric value you would like
to use in your code. However, there are some that are more common to work
with, and these would include:
Bit varying(n)
Double precision
Integer
Float
Bit
Real
Decimal

Literal strings
Another thing that you can take a look at and work with when you are in SQL is
‘literal strings.’ These will consist of a series of characters, such as a list of
names and phone numbers, that will be specified by the user or the database. For
the most part, you will see that these strings will hold onto a lot of data which
has similar characteristics that go with it.
Any time that you are working with literal strings, you will sometimes run into
trouble specifying what kind of data you would like to use. As a result, you will
spend your time specifying the type of string that you would want to use to
ensure that it all works. It is good to understand that when you work to make
these strings, especially if the string will end up being alphanumeric, you will
need to make sure that these are quotes that can go around the world. You have
the choice to go with either the single or the double quotation marks on this one,
you should just make sure that you use it the same on both sides of the word to
help the compiler out.

Boolean values
You are also able to work with what are known as Boolean values. These
Boolean values are important because they will perform a lot of different
functions inside the SQL system, and that can make it easier to work on some of
the searches that you want to do. When you work with Boolean values, there will
be three options of what will come up. These three options are true, false, and
null.
As you are working with the Boolean values, you will also find that using these
values can be helpful when you want to compare several units of data inside of
your table. You would be able to use those units and figure out if they are
matching or not and then will receive the right answer based on the Boolean
values. For example, you would be able to use this in SQL to specify the
parameters of a search, and all of the conditions that come back to you will
either be true, false, or null based on the things that you are trying to compare.
With these kinds of values, you should note that it will give you the results only
when the answer will be true. If the answer to these values ends up being null or
false, the data will not be retrieved out of the database for you or for the user.
However, if you end up with a value that is true, you can notice that all the
information is true and it will show up for you.
A good way to look at this is when your user is in the database and would like to
do a search to find something there. If the keywords of the product match what
the user is typing into the search bar, then true answers will show up while
everything else will stay away.
If you have your own website and you sell things online, you will find that you
will spend a lot of time working with these Boolean values. These values will
ensure that you can get the right results to show up in your program. So, if the
user goes through and types in a keyword that they would like to be able to find
inside of the code, the Boolean value would be able to look at that and find the
results that would fit in.
Don’t worry if this sounds complex, the SQL system is capable of helping you
get this done in a simple manner so that your customers will find the things that
they want without having to worry or fight with the website.
There are many different applications where you can use some of the Boolean
expressions in SQL, but as a beginner, this is probably the method that you will
use the most often. You are also able to use it when you want to look through
your database and find specific answers to questions, or when you are looking
through the store or program and want to find specific information. When you
add some of this information into tables into SQL, you can speed this process up
more than ever before.
It is important to remember how these Boolean results will work. They are in
charge of deciding whether something matches up with what you are searching
for. If something does match up with the keywords that you place into the
system, then they will show up. But if other objects or items do not match up
with this, then they will be shown as false or null and will not show up.
Let’s say that you are using a website to sell some of your products, for example,
clothing. Someone comes onto your site and wants to look for dresses they can
use for special occasions. If they type in the word ‘dress’ on the search bar, you
want to make sure that they can see the products that they want, rather than
something else. This means that dresses should show up on the screen after the
search is done rather than shoes or accessories.
With the Boolean values, this will happen. If the user inputs ‘dress’ on the
system, the Boolean value will go through each item and check to see whether
they are true to this statement. If the item has the word ‘dress’ in it, then these
will show up on your screen. If the item does not have that keyword with it, the
Boolean value will see this as a false statement and will not list it up on the
screen. As long as the Boolean value is working the way that it should, your user
can get the items that they want, and only these items will show up on the
screen.
This can be incredibly useful for anyone who is selling things online, especially
if they have a large inventory to choose from and need the program, such as
SQL, to sort through a ton of data to figure it out. The Boolean values will do all
the work for you to help prevent issues.
As you can see through this chapter, there are many data types that you can work
with inside of SQL to make your searches and your program easier and simpler.
Each data type will work differently so that you will be provided the right results
and get more than what you need.
Chapter 4

How to Manage Objects

This guidebook has taken a lot of time to look over many different topics when it
comes to SQL, such as which data types you should use to work with your
database in SQL. We even spent some time looking at the various commands
that you would be able to choose when you are in SQL so you can initiate
queries and search around inside the database.
Now that you have some of these basics down, it is time to move on to learn
about the steps that you should take when you want to manage the objectivity
that comes in the database. There are many things that we would be able to touch
upon with regards to this in the guidebook, but some of the ones that we will
spend our time on include tables, views, clusters, sequences, and synonyms.
Let’s start looking at these right now to help you understand how all of them will
work in your code.

What is the schema?


When you are working with what is known as a ‘schema’ inside of SQL, you
should always think of it as using a set of objects that are already found inside of
the database, but which will be linked to just one user on the database, rather
than being linked to all of the users. The user who has the access will be the one
who is the owner of the schema, and they will be the ones you can set the
objects. These objects will then be linked directly back to the username that the
owner picked. The user will have the power to generate their objects, and then
when this is done, they can generate their own schema. This allows the user to
have a ton of control over what is found in their databases and they could have
the control to change it as much as they want.
You will find that this can be helpful in several ways. Let's say that your users
just want to place an order with you. If they have their own account and schema,
they would be able to make an order, and then they would be able to change or
delete that order if they so choose.
Another example of this is when the user is trying to set up their own account in
your store. This is something that they can sign up for and then they will have an
account for your store. This is something that they can choose to do, and then
they will go through and pick out the username and the password that they
would like to use. You, as the administrator of the site, can approve these.
After the user has been able to set up their own account, they will have access to
all parts of the database that pertain to them. They can make changes as well,
such as updating their address, changing their payment options, and even making
changes to the orders that they placed. In addition, any time that the user would
like to be able to get into their account, all they need to do is use the username
and password that they picked the first time and log in to mess around on the
database.
Let's take a better look at how this will work by bringing out an example. Let's
say that you are the person who has the credentials that are needed to log in. For
this example, we will use the username ‘PERSON1.’ You can decide what you
would like to place inside this database and you can even create a brand new
table, for this one we will call it ‘EMPLOYEES_TBL.’ When you then go into
the records, you will notice that for this new table, it will be called PERSON1
EMPLOYEES_TBL. This is how others will see the table name as well so they
know who created the table. The schema will be the same for each person who
created this table and owns it.
When you or your user would like to access their own schema, one that is
prepared already, you will not have to list out the exact name of the schema.
Instead, you would simply need to pull up the name that you gave it. So, for the
example that we went through before, you would be able to call up
EMPLOYEES_TBL. Remember that this is just with schemas that are in your
own account. If you would like to be able to pull up schemas that are present
somewhere else, you must add the username ahead of it.

How to create a new table


There are many times when you are creating something new in a database, and
you will need to bring out a table. These tables are nice because they can store
and present the information that you would want to use. You will find that SQL
makes it easy to create tables, and you will then be able to add information as
needed. Whenever you want to create a new table, you just have to use the
simple command of ‘CREATE TABLE.’ This command will allow you to bring
up the table and start using it, but if you would like to fill it in and make the table
look a certain way, there will be a few more steps that you will need to
accomplish.
It is important to think about what you would like to have in the table, how you
would like the table to look, how big it should be, and other information about
the table to ensure that it is made properly. Almost all of the versions of SQL
will provide you with characters that will make it easy to submit or terminate a
statement to the server. With ORACLE, the semicolon will be the option that
you would use, but with the Transact-SQL version, it is better to work with the
GO command. But for most of these versions, you would be able to use the
CREATE TABLE command and then when you are ready, you can start filling
them out.

How to create a table with one that already exists


There will be times that when you are working with SQL where you will want to
take the information that you have from one table and then use that information
to create a new table. This is something that you can do with SQL, you just need
to learn the right commands to make sure that it works right. The commands that
work the best for making this happen include the ‘CREATE TABLE’ and the
‘SELECT’ commands. Once you have been able to use these two commands,
you will see that it worked to create a new table that will have the same
parameters and definitions as your older table. This is a good feature to use when
you would like to create a new table that you can customize, but it would have
the information that you need from an older table.
There is a little bit of coding to make all of this work for your needs. If you
would like to take one of your older tables and use it as the basis of your new
table, you would be able to use the following syntax:
CREATE TABLE NEW_TABLE_NAME AS
SELECT [ “|COLUMN1, COLUMN2]
FROM TABLE_NAME
[ WHERE];
As you take a look at this syntax, you should be able to see that the new syntax
will use the keyword SELECT. This is the right keyword to use here because it is
something that you can bring out any time that you would like to work on a
query for that particular database. This SELECT keyword will help you to work
on your new table, even while you are creating it, with the help of your search
results.
How to drop tables
The next thing that we will work on doing with the SQL system is how to drop
tables. If you use a new keyword, the keyword ‘RESTRICT’ and then you
reference a particular table by using the view or the constraint that is set up, the
command ‘DROP’ will be used, but it will give you a message alerting you that
there is an error in the system. It is also possible to add in the ‘CASCADE’
command along with the DROP command. This will make sure that the DROP
command will work properly and that all the views and the constraints that are
inside of your table will be dropped. To ensure that all of this will work out well
for you, you can use the following syntax to drop a new table:
DROP TABLE TABLE_NAME [ RESTRICT | CASCADE]
Any time that you are interested in dropping your new table inside of the SQL
database, you should make sure that you are telling the program who is the
owner of this new table that you are working on. This is not always necessary,
but it is a good habit to get into. This will ensure that you do not drop the wrong
table and it will often help to prevent loss of information inside of the table. If
you have access to some of the other accounts inside of your database which is
not your own, it is important that you check that you are working inside the
account that you want so that you do not change the wrong things and have to fix
that mess later on.
Since you will work with a lot of information and databases when you work with
SQL, it makes sense that these tables are an important part of working inside the
SQL system. These tables will help you to gather information and present it in a
way that you are easily able to read. The tables will then be able to take the
information, or perhaps the products that you would like to sell, and they can
present them to you in a way that is easier for you to look through. Or, you can
set up the table so that it is easier for the user to look at it when they are on your
website. As you can see, creating these tables is not something that has to be too
difficult to work with, but they will certainly help you to keep the information in
your database as safe as possible.
Chapter 5

How to Do Your Own


Search Results Through SQL

As we have gone through this guidebook, we have spent a lot of time talking
about search results and how SQL can help out with this. You can use SQL to
make it easier for you and for your users to search for terms or items and have
the right things show up. This is a great way to sort through all the information
that is inside of the database, so you can organize it the right way and ensure that
you are getting the right things.
Once you have set up your own database for your business, and you have taken
the time to learn how to create some of your own tables, it is now time to learn
how to do various search queries on this system. You can make the SQL
language work for you to ensure that you can find any result that you would like
as long as that information is found in the database. You do need to make sure
that you have set up the database in the proper way so that your search will find
the right information without encountering any kind of issue.
A good way to think about it is that there are times when people will come to
visit your website, and they are there because they are looking for some
particular product that you are trying to sell. Are you more interested in working
with a database that is slow and brings back the wrong results for your user? No,
this will make the user mad, and they will go and use a different store for their
needs. It is much better to go with a database that is set up right so that it is fast
and will return the results that are needed. Let’s take a look at how you would be
able to set up your queries the right way so that the database will return the best
results for you.

How to create a new query


The first thing that we need to take a look at is how to create a new query. Before
you even start this process, just keep in mind you are basically sending out
information to the database that you already set up. Make sure that you are using
the right command, which in this case will be the SELECT command so that you
can send out the query that you are planning to use.
One example that you can look at for this is when you are working with a table
that is responsible for holding onto all of the products that are in your database.
To do this, you would just use your SELECT command to find out which
products are on that table. Your user will then be able to type in the specific
products that they are interested in finding, such as your best-selling items, ones
that fit a certain price point, size, color, or brand, and so on. You will also be
able to use any type of query that you want to make sure that the user can get the
product that they want out of your database if it is there.

How to work with the SELECT command


Any time that you are on your website, or you would like to create a new query
inside of your database, you will also be able to use the SELECT command to
make this happen. This command can take over the tasks of starting and
executing the queries that you are trying to send out to the database and in most
cases, you will simply need to add something into the statement rather than
sending out the SELECT command. You can add anything that you would like
such as the brand of the item and more before using the command.
Whenever you are ready to work with the SELECT command while working
with SQL, there will be four main keywords that you will need to watch out for.
Remember that these are commonly known as the four clauses. These clauses
are listed below:
SELECT
This command must be combined with the ‘FROM’ command to obtain
the necessary data in a format that is readable and organized. You will
use this to help determine the data that will show up. The SELECT
clause will introduce the columns that you would like to see out of the
search results, and then you can use the FROM to find the exact point
that you need.
FROM
The SELECT and the FROM commands often go together. It is
mandatory because it takes your search from everything in the database,
down to just the things that you would like. You will need to have at
least one FROM clause for this to work. A good example of a syntax
that would use both the SELECT and the FROM properly are these:
SELEC [ * | ALL | DISTINCT COLUMN1, COLUMN2 ]
FROM TABLE1 [ , TABLE2];
WHERE
This is what you will use when there are multiple conditions within the
clause. For example, it is the element in the query that will display the
selective data after the user puts in the information that they want to
find. If you are using this feature, the right conditions to have along with
it are the ‘AND’ and ‘OR’ operators. The syntax that you should use for
the WHERE command is this:
SELEC [ * | ALL | DISTINCT COLUMN1, COLUMN2 ]
FROM TABLE1 [ , TABLE2];
WHERE [ CONDITION1 | EXPRESSION 1 ]
[ AND CONDITION2 | EXPRESSION 2 ]

ORDER BY

You can use this clause to arrange the output of your query. The server
can decide the order and the format that the different information comes
up for the user after they do their basic query. The default for this query
will be organizing the output going from A to Z, but you can make
changes that you would like. The syntax that you can use for this will be
the same as the one above, but add in the following line at the end:
ORDER BY COLUMN 1 | INTEGER [ ASC/DESC ]

All of these will need to be in place if you would like to see the SELECT
command working properly and pulling out the right information that you are
searching for with your query into the database.

How does case sensitivity work?


As you are doing things inside your SQL database, you will not need to worry so
much about the case sensitivity that you put in as you would with some of the
other coding languages that you may have used in the past. You can work with
both the upper case and the lower case letters that you would like, and they will
work the same when you do your own searches. You even have the choice to
look for the clauses and the statements and see how those will show up in your
code.
Now that we have said this, there will be some times when this case sensitivity is
really important. For example, let’s say you’re in a situation where you are
working with objects of data. For the most part, that data that you will use will
be written in upper case letters. The reason for this is because it will let other
users see that something is consistent with the code and they will know why. It
makes the code look better and makes much more sense as well.
Without this rule with the upper case, you would end up with one user typing in
‘JOHN’, and the other user will go with John and still, another user may go with
john. A beginner who goes through the SQL language may be wondering if these
mean the same things or not, and this can get confusing. It is better to have
everything in upper case so that it matches and some issues with writing this
code will be avoided.
Those who work with the SQL language agreed that using an upper case format
was the best idea for avoiding this confusion because these are easier to read,
and it matches up with what you may have done in some other databases that
you worked with. If you are not using this upper case format when you are
writing things out, you need to at least go with another method that will keep
your titles consistent with what you are doing. If you write out all the names
with the format of ‘Name,’ then this is the way that you will do it with all of
them. This will help you to keep track of what you are doing and will make the
database work better.
There are also many times when you will work with transactions in your
database as well as the queries that we talked about earlier, and sometimes these
will go together. These transactions are really important, although you may feel
that this is some unimportant information that the user is not going to care all
that much about. But if you don't use case sensitivity the right way, or make sure
that the table is set up the way that it should be, you will end up with the wrong
results showing up and everyone getting frustrated. No one wants to type words
into a query and find out the results that keep coming up have nothing to do with
what they want.
When you are creating a new database and working inside of it, you must make
sure that the query is set up well. This will make it easier for your user to find
the products and other items that they are looking for. No user wants to come
onto your page and run into issues with finding the information that they need.
When the user types in the keyword, they want to be able to get the right
information.
Imagine how well it would go if the user was on your website and typed in the
keywords for what they are looking for, and then the wrong product came up?
Let’s say that they went on and started looking for some new boots. If they typed
that in and started getting results for kids’ toys, they probably would be really
mad at it. Most people would not even try it a second time and would leave the
page to try some other site, leaving you without the sale.
Working with the right queries and making sure that they work the right way
with your database is so critical so that the above scenario does not happen. You
want to make sure that when the user types in a keyword that they want to use,
they can get the items that match with what they are searching for. These queries
can make sure that you can keep the customer happy, and it will avoid a ton of
frustrations that will come from not being able to find what they want on your
website.
There are a lot of people who will use this kind of database to sell a variety of
products to their customers. Even if this is the way that you would like to use the
database, there will still be times that you would want to make sure that there is
a good search function for your user. If the user wants to be able to look through
the database and find specific information, such as their account, information on
which payment method they have available, or what kind of services you can
provide, you will still want to make sure that you have the transactions set up so
that it goes smoothly. Working to make sure that the database is set up well so
you and the user can find what they want when they do a query in the search bar
will ensure that the user is happy and that your business can run smoothly.
As a beginner, it is important that you learn how to set up the right queries that
can be used inside of your database. This is important to help organize your SQL
database and make sure the user finds what they’re looking for. This is important
whether you are trying to sell products on your website, whether you want to
keep track of payment, and other personal information for the customer or you
want to use the database for another reason. Make sure to use some of the steps
that we outlined earlier in this chapter to help you set up the database in a
manner that makes a lot of sense based on what your users need and will provide
the right information as soon as a customer does a search on your database.
Conclusion
Thank you for making it through to the end of this book, let’s hope it was
informative and that it was able to provide you with all of the tools you need to
achieve your goals, whatever they may be.
The next step is to get started with using SQL as the programming language that
you need to take care of all your database needs. There are a lot of different
databases out there, but if you want your company to provide good customer
service, there isn’t a better database to work with than SQL. SQL is fast, has
been around long enough that it has a solid reputation, and so much more.
This guidebook has spent some time going over all the things that you will need
to know to get started with the SQL language. Whether you are storing some
important personal information about the customer on the database or you would
like to use it to set up your online store, SQL can help you get started. We will
take a look at how to work with SQL how to create tables, some of the
commands that you can use, and so much more. When you are done with this
guidebook, you are certain to know some of the basics of working with SQL and
can understand some of the basic components that you can work with.
When you are ready to learn more about how SQL works and how you can use it
in your own programming to keep information organized and to work on your
database, make sure to check out this guidebook to help you out.
Finally, if you found this book useful in any way, a review on Amazon is always
appreciated!

You might also like