Coding4women Mainfile
Coding4women Mainfile
WOMEN
Diana Adamczyk, Daisy Murray
WHAT YOU WILL ACHIEVE BY
COMPLETING THIS COURSE
The goals of the Go project were to eliminate the slowness and clumsiness of software
development at Google, and thereby to make the process more productive and scalable.
The aims of Go are to be expressive, fast, efficient, reliable and simple to write.
•Simple Syntax
•Compiled Language
•Statically typed
•Concurrency
•Dependency management
- please log onto your Discord Account, you will find this link
- we will share resources here
WEEK 1
•Introductions
•Write your first functions!
•Installing Go and VS code
•Questions?
02/28/2024
PASTE THE FOLLOWING INTO
YOUR FILE
Add picture house and door
The body of each function is enclosed in curly brackets. This is how Go knows
where each function begins and ends
func main () is special….
When you run a program written in Go, execution begins at the main function in the
main package. Without main the Go complier will report an error, because it doesn’t
know where the program should start.
COMMENTS – TO MAKE YOUR
CODE MORE READABLE
//this is how you add a comment
/* you can block out several lines of
cooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
oooooooooooooooooooooooooooooooooooooooode like this */
WHY DIDN’T
THIS RUN?
Opening curly brackets need to be on same line
as the func declaration
WHY DIDN’T THIS
RUN?
No package was declared, every file needs to be within a package.
WHERE
DOES A GO
PROGRAM
START?
A program starts at the main function
in the main package
LET’S CREATE OUR FIRST
PROGRAM IN GO!
1. create a file called “ isAlpha.go”
inside, create a function “PrintAlphabet” that prints the Latin alphabet in lowercase
on a single line.
A line is a sequence of characters preceding the end of line character ('\n').
To run your code type go run <name of program>
The ‘go run’ command executes the program. Your can type in the file name
‘main.go’ or ‘.’ which means the current directory file I am in.
inside, write a function “PrintDigits” that prints the decimal digits in ascending order
(from 0 to 9) on a single line.
A line is a sequence of characters preceding the end of line character ('\n').
EXERCISE 3
Write a file called “reverseAlphabet.go”
02/28/2024
NOW UPLOAD YOUR WORK!
git add .
git push
02/28/2024
IMPORTANT COMMANDS
FROM THE TERMINAL
Use these commands to navigate from the terminal:
02/28/2024
WEEK 2
By the end of this lesson
-create more functions
- learn about variables and data types
- perform operations
WHAT WE DID LAST WEEK
- set up
-made our first function
ANY
QUESTION
S?
VARIABLES
A variable is a name that represents data stored in the computer’s memory.
All variables when declared, whether explicitly or implicitly must have a type.
A rune represents a Unicode code point, which is an integer value that corresponds
to a particular character or symbol.
Runes allow for the representation of characters and symbols from many different
writing systems and languages.
Variables that are not set to a value, are given their zero value
“string sentence”
WHEN NAMING A VARIABLE
Rule Example
CANNOT be a key word break, continue, func , main
CANNOT contain arithmetic operators a+b%c
CANNOT contain punctuation/special characters &%$*£,!
CANNOT contain spaces (only underscores) my_msg
MUST start with a letter msg
CAN contain numbers elsewhere msg1
CAN contain mixed case camelCase
QUIZ ON VARIABLES
Q1. How do you (explicitly) declare a variable? What is the key word?
1. var
2. var <nameVariable> type
3. variable name string
Can you list some basic types for variables?
1. Bool
2. String
3. int
4. rune
5. byte
Q3. Which of these variables is correctly initialized?
1. variable a = “Daisy”
2. var b string = “Daisy”
3. var c string = Daisy
FUNCTIONS
A block of code that performs a specific task
or returns a value.
This code calls the add function with the arguments 2 and 3, and assigns the result (5) to the variable sum.
Go functions accept 0 or more parameters (inputs)
So far we have just been printing values directly onto the terminal and then the computer
forgets them!
However, if you want to keep the values to use, add a ‘ return ‘ keyword to the function.
You state what type of variable(s) you are returning. It has to be the last line of your
function.
You can invoke a function by calling it (i.e. writing it’s name) and you can pass arguments
inside the brackets
Things to keep in mind!
when variables are declared, they either explicitly or implicitly are assigned a type even
before your program runs.
Go requires that every variable you declare gets used somewhere in your program
You can assign new values to existing variables, but they need to be values of the same
type.
02/28/2024
LOGICAL OPERATORS
02/28/2024
EXERCISE
Create a function called IsEven
When you input a number to the function, it will print to the terminal “Even” if the
number is even, “Odd” if the number is odd.
SCOPE OF VARIABLES
Global scope: the variables with such scope are visible and available in all files of a
package.
Local scope: the variables are only known within that function;
G lo
bal
sc o
Local scope
pe
Local scope
Local scope
02/28/2024
02/28/2024
CONSTANT
•A constant is a name for a fixed value.
•The value of a variable can vary, but the value of a constant must remain constant.
.go
Q2. Are these variables the same?
CHALLENGE go/exercises/lasagna/edit
CHALLENGE
Implement a function which will convert Celsius to Fahrenheit. Types of
temperatures are float32 which are aliased to Celsius and Fahrenheit for you.
02/28/2024
TYPE CONVERSION
You can convert some data types, but not all types can be converted to each other.
02/28/2024
WHAT
WE’RE Arrays
LEARNIN
G THIS Slices
WEEK
02/28/2024
ARRAYS
An array is a sequence of elements of a specific length.
When creating an array you separate an the values using commas, when printing it is
shown with elements separated by spaces.
02/28/2024
ARRAYS Here we are telling the computer the
type of the variable ‘fruit’ is an array of
length four and the element type is
string.
Creating an array variable without assigning a
value will create an array of the specified length
with the zero value of the given element type
[ ] = this is an array
4 = the array will be of length four
string = the elements of the array will be strings
{ } = the contents inside the curly brackets is the contents to put in the array
02/28/2024
ARRAYS
Using the … syntax allows the array to automatically determine the number of
elements.
So this
02/28/2024
ACCESSING ARRAY VALUES
Elements in an array can be accessed by using the index of the value you want.
The index is a numerical value that starts at 0.
02/28/2024
ACCESSING ARRAY VALUES
Multiple elements can be accessed by using creating a slice using : to tell the code
you want to look at multiple ___ index points.
The rule for this syntax is arrayName[startIndex:endIndex] where the starting
index is included but the ending index is excluded.
02/28/2024
ACCESSING ARRAY VALUES
02/28/2024
SLICES
Slices can be made as a subsection of an existing array or they can be declared in the
same way as arrays except no element count is given.
When made directly Go will create an array underlying array of the appropriate
length and capacity, which will change along with the slice.
Unlike arrays which have a static length slices can have variable lengths. This makes
them more flexible and powerful as the slice can grow or shrink to suit your current
needs.
02/28/2024
SLICES
There are three important functions to know when using slices
len retrieves the current number of elements in a slice (the length of a slice)
cap retrieves the number of elements the slice can hold before it must be resized (the
capacity of a slice)
append adds an element to the end of a slice
The len and cap functions can also be used on arrays however append is only for
slices as arrays cannot change their length
02/28/2024
It is important to know that is you wish to copy a slice or array you must use the
built-in copy function
Result of code:
The copy function takes the destination slice as the first argument and the source slice
as the second, and both slices must be of the same type.
The one major thing to note: the lengths of both destination and source slices do not
have to be equal. It will only copy up to the smaller number of elements. So if you
attempt to copy to an empty or nil slice, nothing will be copied.
02/28/2024
If you don’t use the copy function then both the original slice and the duplicate/sub
slice will both be changed
Result of code:
As you can see after changing an element in newNum, the corresponding element in
numbers also changed.
02/28/2024
MAPS
A map is an unordered collection of key-value pairs, where each key is unique.
02/28/2024
MAPS
To create a empty map you can use the make function, this initialises the map so it is
an empty map not a nil map.
The difference between a nil map and an empty map is how data can then be added
to them.
For a nil map data can only be added by setting the variable to a map of the same
type as specified. This will initialise it.
02/28/2024
MAPS
To create a empty map you can use the make function, this initialises the map so it is
an empty map not a nil map.
The difference between a nil map and an empty map is how data can then be added
to them.
For a nil map attempting to add data directly to the map will result in an error
02/28/2024
MAPS
To create a empty map you can use the make function, this initialises the map so it is
an empty map not a nil map.
The difference between a nil map and an empty map is how data can then be added
to them.
For an empty map a new map can be assigned to them or you can add a new value
pair directly without an error message.
02/28/2024
MAPS
Instead of numerical index points the values are accessed by their keys.
What do you think is the output of the following code:
ANSWER: 3
02/28/2024
MAPS
Any value can be accessed by specifying the associated key. A second value can be
returned to check if the key is in the map.
02/28/2024
WEEK 4
WHAT WE DID LAST WEEK
• Arrays
02/28/2024
THIS WEEK
•Slices
•Maps
•If – Else statements continued
•For loops
02/28/2024
HOMEWORK
Debbie
Yadira
02/28/2024
You can only have 1 func main
within a program
Func main(){
//your code
}
02/28/2024
02/28/2024
FLOW CONTROL
USING BOOLEAN LOGIC
•The order in which instructions are carried out
•There is more than one way your program can run depending on the data you feed it.
The computer will run a certain path depending on the data and the conditions you
have set it.
•True -> outcome1
•False -> outcome2
IF STATEMENT
•How do you decide if to eat or not?
•How do you decide if to visit the doctor or not?
•How do you know if to go to bed or not?
Used when you are more interested in value rather than location
The for-range loop can be used to access individual characters in a string.
terminal output
The for-range loop can be used to access individual key-value pairs in a map also
EXERCISE
Create if else statements to print different messages depending on whether the person lives there, is
Daisy, or is neither.
NAVIGATING YOUR
FILE SYSTEM
learning Bash scripting and navigating the
command line is an important skill for coders,
regardless of your specific programming language.
02/28/2024
02/28/2024
02/28/2024
02/28/2024
02/28/2024
02/28/2024
FILE STRUCTURE OF GO
Go programs are organized into
packages.
A package is a collection of
files in the same directory that
are compiled together.
Functions, types, variables, and
constants defined in one source
file are visible to all other
source files within the same
package.
A module is a collection of related Go packages that are released together.
You only need 1 module per project.
The module keeps your project contained and therefore exportable – it will keep tabs
on all the the packages, subdirectories, files, functions in your project.
Each module has a unique module path, which is specified in the go.mod file at the
root of the module. The go.mod file also specifies the version of the Go language
that the module is compatible with, as well as any dependencies(external
packages/libraries you imported) that the module requires.
HOMEWORK: WORD FREQUENCY
COUNTER
Objective: Write a Go program that reads a list of words and counts the frequency of
each word.
Instructions:
1.Initialize a Slice: Create a slice of strings containing a list of words. This can be either
hardcoded or taken as input from the user.
2.Count Word Frequencies with a Map: Create a map where the key is a word (string)
and the value is its frequency (int). Loop through the slice of words, and for each word, if
it's not in the map, add it with a value of 1. If it's already in the map, increment its value.
3.Output the Results: Loop through the map and print out each word and its frequency.
EXAMPLE
words := []string{"apple", "banana", "apple", "orange", "banana", "apple", "kiwi", "kiwi", "kiwi"}
02/28/2024
Hints:
•Use a for loop to iterate over the slice.
•Use Go's map data structure to maintain a count of each word.
•Remember that checking a key in a map that doesn't exist will return the zero value
for the map's value type. In the case of an int, this is 0.
02/28/2024
WEEK 5
02/28/2024
WHAT DID WE DO LAST
WEEK?
Flow control : if-else statements
For loops
File structure of Go
Working in VS code
HOW DOES THE WEB WORK?
WHAT WE WILL DO
oSetup a project directory which follows the Go conventions.
oStart a web server and listen for incoming HTTP requests.
oRoute requests to different handlers based on the request path.
oManage errors
oload HTML pages and use templates
oServe static files like images and CSS
STEP 1.
Lets create a fresh repository
02/28/2024
FIRST STEPS
Set up your main file
HTTP (Hypertext Transfer Protocol) is a protocol used to transfer data over the web.
It is the foundation of the World Wide Web, and it is used by web browsers and
servers to communicate with each other.
When you enter a URL in a web browser, the browser sends an HTTP request to the
web server hosting the requested resource (such as a web page or image).
The server then responds with an HTTP response, which includes the requested
resource (or an error message if the resource cannot be found).
To use this handler function in a web application, you need to use the
http.HandleFunc() function.
When a client makes a request to the server, the default server that Go uses
(DefaultServeMux) will look for a handler function to process the request and
generate a response.
STEP 2 - DATA
We are going to create a struct to hold the data we want to post to our website.
WHAT IS A STRUCT?
structs are a collections of fields.
For example if you create a struct for someone who has a bank account, inside you
would have fields of data relating to
- name string
-bank account number int
-account balance int
DECLARING AND INITIALIZING A
STRUCT
In web development, JSON is commonly used as a format for transmitting data between
a web server and a client application. It’s easily compressed, quick to transmit lots of
data and easy for humans to read and write.
For example, when a client makes a request to a web server, the server might respond
with JSON-encoded data that the client can then parse and display in a web browser or
mobile app.
JSON tags specify the names of the JSON fields that correspond to each struct field.
For example, the Go Id field has a JSON tag of "Id", it will look for the JSON field
with the name "Id".
Similarly, the Go RecipeName field has a JSON tag of "Recipe Name” which means
that Go will look for the JSON field with the name "Recipe Name".
WEEK 6
WHEN CREATING OUR PROGRAM, ONE OF THE
FIRST STEPS IS TO CREATE A MODULE. WHAT IS
THE COMMAND TO CREATE A MODULE, AND WHAT
IS A MODULE?
We are going to create a structs to hold the data we want to post to our website.
HOW OUR WEBSITE WORKS
When a client (such as a web browser) wants to access a web page or web
application, it sends an HTTP request to the server that hosts the web page or
application. The server receives the request, and then passes the request to the
appropriate handler function, which generates a response that is sent back to the
client. The client then receives the response and renders it in the browser window.
The client-server relationship is typically based on the HTTP protocol, which is the
standard protocol used for communication between web browsers and servers.
The client, your computer will make a request to the server for a connection and for
data.
HANDLERS
Handler functions are functions that are called by servers to process incoming
requests and generate responses.
STEP 4 CREATE A GLOBAL
VARIABLE OF []STRUCT
RECIPE
We have created a container to store our recipe.
We now want to duplicate this format to store ALL of our recipes that’s why we
create a slice of recipe.
STEP 5 CREATE FUNCTION TO
‘FETCH’ DATA
HTTP.GET
The HTTP GET method is used to read (or retrieve) a representation of a resource.
The go package http has a function Get that sends a GET request to the specified url
you want to get the information from.
http.Get(“url”)
HTTP METHODS
POST – Creates
GET – Reads
PUT – Updates
DELETE – Deletes
GET and POST are the only methods we will be using for our website.
(part of protocol)
.57 seconds
IO.READALL
io package has a function ReadAll which will take a file/some data and convert it
into a []byte. The []byte can then be edited or more easily converted into other data
types, depending on the desired outcome.
[]byte are also the required input type for a lot of functions that allow you to write
data to a specified location. Such as the next function we will use.
JSON.UNMARSHALL()
This function takes two inputs:
A []byte which represents the data to be ‘unmarshalled’
The location where you want the data to go.
We are going to create a structs to hold the data we want to post to our website.
HOW OUR WEBSITE WORKS
When a client (such as a web browser) wants to access a web page or web
application, it sends an HTTP request to the server that hosts the web page or
application. The server receives the request, and then passes the request to the
appropriate handler function, which generates a response that is sent back to the
client. The client then receives the response and renders it in the browser window.
The client-server relationship is typically based on the HTTP protocol, which is the
standard protocol used for communication between web browsers and servers.
The client, your computer will make a request to the server for a connection and for
data.
HANDLERS
Handler functions are functions that are called by servers to process incoming
requests and generate responses.
STEP 4 CREATE A GLOBAL
VARIABLE OF []STRUCT
RECIPE
We have created a container to store our recipe.
We now want to duplicate this format to store ALL of our recipes that’s why we
create a slice of recipe.
STEP 5 CREATE FUNCTION TO
‘FETCH’ DATA
HTTP.GET
The HTTP GET method is used to read (or retrieve) a representation of a resource.
The go package http has a function Get that sends a GET request to the specified url
you want to get the information from.
http.Get(“url”)
HTTP METHODS
POST – Creates
GET – Reads
PUT – Updates
DELETE – Deletes
GET and POST are the only methods we will be using for our website.
(part of protocol)
.57 seconds
IO.READALL
io package has a function ReadAll which will take a file/some data and convert it
into a []byte. The []byte can then be edited or more easily converted into other data
types, depending on the desired outcome.
[]byte are also the required input type for a lot of functions that allow you to write
data to a specified location. Such as the next function we will use.
JSON.UNMARSHALL()
This function takes two inputs:
A []byte which represents the data to be ‘unmarshalled’
The location where you want the data to go.
http.ListenAndServe(“:PortNumber”)
1.
2.
• A boilerplate in HTML is a
template you will add at the start of
your project. You should add this
boilerplate to all of your HTML
pages.
WHAT IS A DOCTYPE IN HTML?
• The doctype tells the browser what version of HTML the page is written in.
WHAT IS THE HTML ROOT
ELEMENT?
• The <html> tag is the top level element of the HTML file
• The head tag and body tag are both nested inside the html tag. (in other words everything
is inside the html.)
• The ‘lang’ attribute sets the language for the page. It is good to include it for accessibility
reasons, so screen readers know how to pronounce the text.
WHAT ARE HEAD
TAGS?
• <head> tags contain metadata
• Metadata is information to be processed by machines
• It describes the data being given to the machine
• The charset metadata attribute tells the machine what character set the page uses.
• UTF-8 is the standard character encoding.
• It supports many languages and can support pages and forms in any mixture of those
languages.
• The viewport meta tag tells the machine how wide to render the page and the initial level
of zoom.
• E.g. if your device was 600px wide, the machine would know to render the web browser
to be 600px wide.
• The X-UA-Compatible meta tag specifies the document mode for Internet Explorer.
• The <title> tag is the name of the tab
• The <link> tag connects the html to a css file
02/28/2024
INSERTING DATA INTO A TEMPLATE
In Go, Every field that you intend to be rendered within a template should be put
inside of {{}}
The dot inside {{.}} is shorthand for the current object.
If you want to access specific fields of the current object, you should
use {{.FieldName}}
RANGING OVER COMPOSITE
DATA
You can do a for loop and range over arrays/maps
{{range …}}{{end}}
WE ARE GOING TO UPGRADE
OUR SERVER
We use NewServeMux to handle our routing
Our website handles many requests (end points), having just 1 handler for “/” GET is
not enough! Our website has more functionality!
We will also use it to read our CSS files
NewServeMux!
NOW LET’S ADD CSS!
To make our page look prettier – we can add CSS
We have to link our HTML document to the CSS which will reads the HTML tags.
We have to link the HTML and the Go.
•CSS stands for Cascading Style Sheets
<header>
MEAN?
<h3> (size of header text)
<p> - paragraph
<footer>
WEEK 8 Finishing the project and final
review
WHAT WE DID LAST WEEK
1 2 3
Create handler Create the HTML Update homepage
function for recipe for the recipe page HTML to make
pages buttons
• Routing logic for the
different recipe end
points
LET’S OPEN UP VS CODE AND
FINISH THIS!
Recipe1 Recipe2
RecipeName: “Hot Dog
RecipeName: “Chocolate Chip
Pretzels”
Cookies”
PrepTime: “30 mins (+ 1.5-2.5
PrepTime: “20 mins”
hours proving time)”
CookTime: “12-15mins”
CookTime: “15 mins"”
ServingSize: 15
ServingSize: 8
Tags: [“Chocolate”, “Cookie”]
Tags: [“Meat”, “Bread”]
Tells the computer where to end the loop – only the code
between range and end will be repeated
Recipe1 Recipe2
RecipeName: “Hot Dog
RecipeName: “Chocolate Chip
Pretzels”
Cookies”
PrepTime: “30 mins (+ 1.5-2.5
PrepTime: “20 mins”
hours proving time)”
CookTime: “12-15mins”
CookTime: “15 mins"”
ServingSize: 15
ServingSize: 8
Tags: [“Chocolate”, “Cookie”]
Tags: [“Meat”, “Bread”]
Tells the computer where to end the loop – only the code
between range and end will be repeated
Recipe1 Recipe2
RecipeName: “Hot Dog
RecipeName: “Chocolate Chip
Pretzels”
Cookies”
PrepTime: “30 mins (+ 1.5-2.5
PrepTime: “20 mins”
hours proving time)”
CookTime: “12-15mins”
CookTime: “15 mins"”
ServingSize: 15
ServingSize: 8
Tags: [“Chocolate”, “Cookie”]
Tags: [“Meat”, “Bread”]
Tells the computer where to end the loop – only the code
between range and end will be repeated
WHAT WILL THE OUTPUT BE
IN THE FOLLOWING CODE?
Recipe1 Recipe2
RecipeName: “Hot Dog
RecipeName: “Chocolate Chip
Pretzels”
Cookies”
PrepTime: “30 mins (+ 1.5-2.5
PrepTime: “20 mins”
hours proving time)”
CookTime: “12-15mins”
CookTime: “15 mins"”
ServingSize: 15
ServingSize: 8
Tags: [“Chocolate”, “Cookie”]
Tags: [“Meat”, “Bread”]
{{range .}}
{{.RecipeName}}
{{end}} Recipe2
Recipe1
OUTPUT: OUTPUT:
“Chocolate Chip Cookies” “Hot Dog Pretzels”
Files
Request
PC
Clients
Listen & Serve
Server Network/Internet Laptop
:8000
Response Mobile
Data
REVIEW OF WHAT YOU HAVE
LEARNT
• Variables
•Functions
•Variable types
•Arrays, slices
•If – else statements
•For loops
•How to upload work onto GitHub
• git add .
• git commit –m “a message”
• git push
This isn’t a memory test. You understand how to chop and change code to fit the
specific needs.
fail fail fail, make mistakes so you can learn and understand!!!
REVIEW EXAM
https://forms.gle/B9NYMnodxiJiGaYH8