Coding Languages For Absolute Beginners 6 in 1
Coding Languages For Absolute Beginners 6 in 1
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
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.
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.
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
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);
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:
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.
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.
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++?
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
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
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
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.
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.
‘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
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
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 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.
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
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
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
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.
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.
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.
These are any of the variables that belong to a particular data type.
Methods
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.
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.
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.
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
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.
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.
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.
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.
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
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.
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
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.
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.
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.
(*)
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.
-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
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.
`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.
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.
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.
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.
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 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.
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;
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
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.
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 where you are going to find the name of the module, and it will also hold
your classes.
__name__
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.
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
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.
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)
def DisplayPostGraduateStudent(self):
print(“Student Name:”, self.name)
print(“Student Rollno:”, self.rollno)
print(“Study Group:”, self.postgrad)
When you type this into your interpreter, you 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’)
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.
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.
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.
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.
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
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:
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.
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
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
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.
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.
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.