Go Programming — Block 1: Learn by Questions, Build by Doing

Go Programming — Block 1: Learn by Questions, Build by Doing

We will start learning Go (Golang) directly, not writing prompts or reading a textbook. The goal is to learn the essential concepts through MCQs, practical problems, working code, and simple explanations.

Our method: Understand a concept → answer a question → use it in a real program → modify the program yourself.

Chapter 1. Getting started with Go

Go is a programming language used to build web servers, APIs, command-line tools, and other software.

MCQ 1 — What does a programmer do?

What is the main purpose of programming?

A. To decorate a computer screen

B. To give a computer instructions to perform tasks

C. To increase internet speed automatically

D. To replace computer hardware

Correct!

Programming means writing instructions a computer can execute, such as calculating a bill or processing exam results.

MCQ 2 — Your first Go program

Go

package main

import "fmt"

func main() {
    fmt.Println("Hello, World!")
}

What will this program display?

Hello

Hello, World!

fmt.Println

Nothing

Check answer

Correct!

fmt.Println() displays the text inside its parentheses. The quotation marks identify the text as a string; they are not displayed.

Understand the program

CodeMeaning
package mainIdentifies this as a program that can run directly.
import "fmt"Makes Go's formatting and printing tools available.
func main()The main function; execution starts here.
fmt.Println(...)Displays text and moves to a new line.
{ and }Mark the beginning and end of a block of code.

You don't need to memorize every detail today. Understand what each line does and use this pattern in your first programs.

Practical task 1 — Run your first program

Create a folder named go-block-1. Inside it, create a file named main.go.

Folder structure:

go-block-1/
└── main.go

Put the following code in main.go:

Go

package main

import "fmt"

func main() {
    fmt.Println("My name is Pramod.")
    fmt.Println("I am learning Go.")
    fmt.Println("My goal is to build useful software.")
}

Run it in your terminal from inside the go-block-1 folder:

Bash

go run main.go

Expected output:

My name is Pramod.
I am learning Go.
My goal is to build useful software.

What you learned: One program can execute several instructions in order. Each fmt.Println() displays a separate line.

Chapter 2. Output, input, and comments

MCQ 3 — Accepting information

Which Go function can read a user's input from the keyboard?

  • A. fmt.Println()

  • B. fmt.Scan()

  • C. fmt.Stop()

  • D. fmt.Display()

Answer: B — fmt.Scan()

fmt.Println() displays information. fmt.Scan() can read information entered by the user.

MCQ 4 — Comments

What is the purpose of this line?

Go

// Calculate the final price
  • A. It calculates the price.

  • B. It displays a message.

  • C. It explains the code to a human reader.

  • D. It creates a variable.

Answer: C. A comment explains code to people. Go ignores ordinary comments when executing the program.

Practical task 2 — Build a personal greeting program

Create main.go:

Go

package main

import "fmt"

func main() {
    var name string

    fmt.Print("Enter your name: ")
    fmt.Scan(&name)

    // Greet the user
    fmt.Println("Hello,", name)
}

Run it:

Bash

go run main.go

Example:

Enter your name: Pramod
Hello, Pramod

Line-by-line explanation

  • var name string creates a variable named name that stores text.

  • fmt.Print(...) displays a message without automatically moving to a new line.

  • fmt.Scan(&name) reads the input and stores it in name. The & tells Go where the variable's storage is so it can put the input there.

  • fmt.Println("Hello,", name) displays the greeting and the entered name.

  • // Greet the user is a comment for the programmer.

For now, fmt.Scan() is enough for simple, single-word inputs. Later, we can learn how to accept full sentences containing spaces.

Chapter 3. Variables and data types

A variable is like a labelled box in which a program stores information.

TypeStoresExample
stringText"Book"
intWhole numbers25
float64Decimal numbers99.50
boolTrue or falsetrue

MCQ 5 — Choose the correct type

You are building a shopping application. Which type is appropriate for storing a product's name?

  • A. int

  • B. bool

  • C. string

  • D. float64

Answer: C — string, because a product name is text.

MCQ 6 — Understand a variable

What will this code display?

Go

price := 100
price = 150
fmt.Println(price)
  • A. 100

  • B. 150

  • C. 250

  • D. An error because variables cannot change

Answer: B — 150. The second assignment replaces the value stored in price. The := syntax creates and initializes a new local variable.

Practical task 3 — Calculate a shopping bill

Suppose a customer buys 3 notebooks at ₹40 each.

Go

package main

import "fmt"

func main() {
    var product string = "Notebook"
    var quantity int = 3
    var price float64 = 40

    total := float64(quantity) * price

    fmt.Println("Product:", product)
    fmt.Println("Quantity:", quantity)
    fmt.Println("Total: Rs.", total)
}

Output:

Product: Notebook
Quantity: 3
Total: Rs. 120

What is happening?

  • product stores the product name.

  • quantity stores the number of notebooks.

  • price stores the price of one notebook.

  • float64(quantity) converts the whole number to a decimal-compatible numeric type.

  • * multiplies the quantity by the unit price.

  • total := ... stores the result in a new variable.

Real-life application: the same basic pattern can calculate an order total, invoice amount, or the total cost of several items.

Chapter 4. Operators and calculations

Operators are symbols that perform calculations or comparisons.

| Operator | Meaning | Example | |---|---|---| | + | Add | 10 + 5 | | - | Subtract | 10 - 5 | | * | Multiply | 10 * 5 | | / | Divide | 10 / 5 | | % | Remainder | 10 % 3 gives 1 | | == | Equal to | age == 18 | | > | Greater than | price > 100 | | && | Both conditions true | age >= 18 && age <= 60 | | || | At least one condition true | day == 6 || day == 7 | | ! | Reverses a Boolean value | !true gives false |

MCQ 7 — Calculate a discount

A product costs ₹1,000 and has a 10% discount. What is the final price?

  • A. ₹900

  • B. ₹990

  • C. ₹1,100

  • D. ₹100

Answer: A — ₹900.

Discount = 1000×10/100=1001000 \times 10 / 100 = 1001000×10/100=100.

Final price = 1000−100=9001000 - 100 = 9001000−100=900.

MCQ 8 — Find the remainder

What does 17 % 5 return?

  • A. 3

  • B. 2

  • C. 5

  • D. 0

Answer: B — 2. Five goes into seventeen three times, leaving a remainder of two.

Practical task 4 — Build a discount calculator

Go

package main

import "fmt"

func main() {
    price := 1000.0
    discountPercent := 10.0

    discount := price * discountPercent / 100
    finalPrice := price - discount

    fmt.Println("Original price:", price)
    fmt.Println("Discount:", discount)
    fmt.Println("Final price:", finalPrice)
}

Output:

Original price: 1000
Discount: 100
Final price: 900

The important idea: A program can turn a real-world formula into repeatable calculations. Later, we will combine this with user input, so you can enter any price and discount instead of changing the code manually.

Chapter 5. Decisions using if, else, and switch

Programs often need to make decisions based on information.

For example:

  • If marks are at least 40, the student passes.

  • If the stock is zero, the product is unavailable.

  • If the bill exceeds a certain amount, a discount applies.

MCQ 9 — Pass or fail

What will this program display?

Go

marks := 65

if marks >= 40 {
    fmt.Println("Pass")
} else {
    fmt.Println("Fail")
}
  • A. Fail

  • B. Pass

  • C. Both messages

  • D. Nothing

Answer: B — Pass. Since 65 is greater than or equal to 40, the first condition is true.

MCQ 10 — When to use switch

Suppose a program offers three menu choices: 1 for viewing products, 2 for adding a product, and 3 for exiting. Which Go feature is especially suitable for handling these distinct choices?

  • A. switch

  • B. float64

  • C. fmt.Println alone

  • D. A comment

Answer: A — switch. It selects an action based on a value, such as the user's menu choice.

Practical task 5 — Student result checker

Go

package main

import "fmt"

func main() {
    marks := 72

    if marks >= 40 {
        fmt.Println("Result: Pass")
    } else {
        fmt.Println("Result: Fail")
    }
}

Try changing marks to 35. The output changes to Result: Fail.

Real-life connection: The same pattern can check eligibility, stock availability, minimum order amounts, or whether a user has permission to perform an action.

One caution: this simple example checks only one subject. A real examination system may need to check each subject separately and apply additional rules.

Chapter 6. Loops and repetition

A loop repeats instructions. Instead of writing the same statement 100 times, you write a loop that runs 100 times.

MCQ 11 — Count from 1 to 5

What will this code print?

Go

for i := 1; i <= 5; i++ {
    fmt.Println(i)
}
  • A. Numbers 0 through 4

  • B. Numbers 1 through 5

  • C. Only 5

  • D. It runs forever

Answer: B.

  • i := 1 starts the counter at 1.

  • i <= 5 continues while the counter is at most 5.

  • i++ increases the counter by one after each iteration.

MCQ 12 — Why use a loop?

You have 500 product prices and need to calculate their total. Which approach is generally more practical?

  • A. Write a separate addition statement for every price.

  • B. Use a loop to process each price.

  • C. Store all prices in one text sentence.

  • D. Manually calculate the result each time.

Answer: B. Loops allow the same operation to be applied to many items.

Practical task 6 — Calculate a total

Go

package main

import "fmt"

func main() {
    prices := []int{100, 200, 150, 50}
    total := 0

    for _, price := range prices {
        total += price
    }

    fmt.Println("Total:", total)
}

Output:

Total: 500

Understand the new syntax:

  • []int{100, 200, 150, 50} creates a slice: a collection of integer values.

  • total := 0 starts the running total at zero.

  • range prices goes through the collection one item at a time.

  • _ means we are ignoring the item's position or index.

  • price receives the current item's value.

  • total += price adds the current price to the existing total.

This is the basic pattern used for adding up shopping bills, summing exam marks, and processing lists of records.

Chapter 7. Functions and reusable code

A function is a named set of instructions that performs a task. You can use it repeatedly without rewriting its internal logic.

MCQ 13 — What is a function useful for?

Suppose you calculate a discount in several places in your application. Why create a function for the calculation?

  • A. To make the code longer.

  • B. To reuse the same calculation and maintain it in one place.

  • C. To prevent all errors automatically.

  • D. To avoid using variables.

Answer: B. A function makes repeated work easier to reuse and update.

MCQ 14 — Understand a return value

What will this program display?

Go

func add(a int, b int) int {
    return a + b
}

If the program calls fmt.Println(add(4, 6)), what is displayed?

  • A. 46

  • B. 10

  • C. a + b

  • D. Nothing

Answer: B — 10. The function adds the two numbers and returns the result.

Practical task 7 — Create a reusable discount function

Go

package main

import "fmt"

func calculateDiscount(price float64, percent float64) float64 {
    return price * percent / 100
}

func main() {
    price := 2000.0
    discount := calculateDiscount(price, 15)
    finalPrice := price - discount

    fmt.Println("Discount:", discount)
    fmt.Println("Final price:", finalPrice)
}

Output:

Discount: 300
Final price: 1700

How it works:

  • calculateDiscount is the function's name.

  • price and percent are inputs to the function, called parameters.

  • The final float64 specifies the type of value the function returns.

  • return sends the calculated result back to the calling code.

  • calculateDiscount(price, 15) calls the function with the given values.

A function like this can be reused across product billing, shopping carts, and invoice calculations.

Chapter 8. Arrays, slices, and maps

These concepts help you store and organize multiple pieces of information.

  • Array: A fixed-size collection.

  • Slice: A flexible collection that can grow or shrink.

  • Map: A collection of key-value pairs, useful for looking up information by a key.

MCQ 15 — Choose the right collection

You want to store a list of product prices, and the list may grow when new products are added. Which is generally appropriate?

  • A. A slice

  • B. A single integer

  • C. A Boolean

  • D. A comment

Answer: A — a slice.

MCQ 16 — Find a value in a map

Consider:

Go

prices := map[string]int{
    "Pen": 10,
    "Book": 50,
}
fmt.Println(prices["Book"])

What is printed?

  • A. Pen

  • B. 10

  • C. 50

  • D. Book

Answer: C — 50. The key "Book" retrieves its associated value, 50.

Practical task 8 — Create a product price list

Go

package main

import "fmt"

func main() {
    prices := map[string]int{
        "Pen": 10,
        "Book": 50,
    }

    prices["Bag"] = 500

    fmt.Println("Book price:", prices["Book"])
    fmt.Println("Bag price:", prices["Bag"])
}

Output:

Book price: 50
Bag price: 500

What this teaches:

  • map[string]int means keys are strings and values are integers.

  • "Book" is a key, and 50 is its value.

  • prices["Bag"] = 500 adds a new entry.

  • prices["Book"] looks up the price associated with that key.

This is useful for simple product catalogs, price lists, and counting items by name. For a real application, also learn how Go indicates whether a requested map key exists.

Chapter 9. Strings and practical text processing

A string is text. Programs often need to combine, compare, search, or transform text.

MCQ 17 — Join two strings

What does this code print?

Go

first := "Go"
second := "Programming"
fmt.Println(first + " " + second)
  • A. GoProgramming

  • B. Go Programming

  • C. first second

  • D. An error

Answer: B — Go Programming. The + operator joins the two strings, and " " adds a space between them.

MCQ 18 — Compare text

What does the expression "Go" == "Go" return?

  • A. true

  • B. false

  • C. Go

  • D. 0

Answer: A — true. The two strings contain the same text.

Practical task 9 — Search for a word in text

Go

package main

import (
    "fmt"
    "strings"
)

func main() {
    message := "Learn Go programming"
    word := "Go"

    if strings.Contains(message, word) {
        fmt.Println("Word found")
    } else {
        fmt.Println("Word not found")
    }
}

Output:

Word found

How it works:

  • strings is a standard Go package for common text operations.

  • strings.Contains(message, word) checks whether the text contains the specified word.

  • The if statement chooses the appropriate message.

This pattern can help search product descriptions, check whether a message contains a keyword, or filter simple text records. The search is case-sensitive: "go" and "Go" are different strings.

Chapter 10. Errors, debugging, and problem-solving

Programming involves finding and fixing mistakes. Three common categories are:

  • Syntax or compilation errors: The code breaks Go's language rules.

  • Runtime errors: Something goes wrong while the program is running.

  • Logic errors: The program runs but produces the wrong result.

MCQ 19 — Find the syntax error

What is wrong with this code?

Go

package main

import "fmt"

func main() {
    fmt.Println("Hello"
}
  • A. The quotation marks are unnecessary.

  • B. The closing parenthesis ) is missing.

  • C. fmt.Println cannot print text.

  • D. Go does not support functions.

Answer: B. The call to fmt.Println must have a closing parenthesis before the closing brace.

Correct line:

Go

fmt.Println("Hello")

MCQ 20 — Find the logic error

A program calculates a discount using:

Go

discount := price * percent

The intended calculation is a percentage discount. What is missing?

  • A. Division by 100

  • B. A loop

  • C. A map

  • D. A comment

Answer: A. The correct calculation is:

Go

discount := price * percent / 100

For a price of ₹1,000 and a discount rate of 10, the discount should be ₹100, not ₹10,000.

Practical task 10 — Handle an invalid calculation

Dividing by zero is not a valid operation for integer division in Go. Check the input before performing the calculation.

Go

package main

import "fmt"

func main() {
    numerator := 10
    denominator := 0

    if denominator == 0 {
        fmt.Println("Error: cannot divide by zero")
        return
    }

    result := numerator / denominator
    fmt.Println("Result:", result)
}

Output:

Error: cannot divide by zero

Why this works:

  • denominator == 0 checks whether the divisor is zero.

  • The program prints an understandable error message.

  • return exits the main function before the invalid division is reached.

  • If the denominator is changed to 2, the program prints Result: 5.

This is a simple example of validating input before using it. Real applications should also check other invalid inputs and return or handle errors appropriately.

Final practical project — Mini billing system

Now combine the concepts from the 10 chapters into one small, useful program.

1. Folder structure

Create a folder called mini-billing containing one file:

mini-billing/
└── main.go

2. Complete working code

Save this as main.go:

Go

package main

import (
    "fmt"
    "strings"
)

func main() {
    var product string
    var quantity int
    var price float64

    fmt.Print("Enter product name: ")
    fmt.Scan(&product)

    fmt.Print("Enter quantity: ")
    fmt.Scan(&quantity)

    fmt.Print("Enter price per item: ")
    fmt.Scan(&price)

    if quantity <= 0 || price < 0 {
        fmt.Println("Invalid quantity or price")
        return
    }

    subtotal := float64(quantity) * price
    discount := 0.0

    if subtotal >= 1000 {
        discount = subtotal * 10 / 100
    }

    total := subtotal - discount

    fmt.Println("\n--- BILL ---")
    fmt.Println("Product:", strings.ToUpper(product))
    fmt.Println("Quantity:", quantity)
    fmt.Println("Subtotal:", subtotal)
    fmt.Println("Discount:", discount)
    fmt.Println("Final total:", total)
}

3. Run the program

Open the terminal inside the mini-billing folder and run:

Bash

go run main.go

Example input:

Enter product name: Notebook
Enter quantity: 5
Enter price per item: 250

Expected output:

--- BILL ---
Product: NOTEBOOK
Quantity: 5
Subtotal: 1250
Discount: 125
Final total: 1125

4. What concepts did you combine?

Code or featureChapter
package main, func main()1
fmt.Print, fmt.Println, fmt.Scan2
product, quantity, price3
Multiplication and percentage calculation4
if conditions5
No loop is needed for this single-product bill6
main() is a function7
No collection is needed for a single product8
strings.ToUpper()9
Validation and early exit10

Notice something important: good programming is not about using every concept in every project. It is about selecting the concepts that solve the problem.

This program intentionally uses only one file. As the application grows to handle many products, you can introduce slices, maps, loops, and additional functions.

One limitation: fmt.Scan(&product) reads only a single word for the product name. Also, this beginner version assumes that the user enters valid numeric input. A production billing system needs stronger input validation and appropriate monetary rounding.

Essential Go syntax reference

Keep this as your quick revision sheet.

TaskSyntax
Display textfmt.Println("Hello")
Read simple inputfmt.Scan(&name)
Create a variableage := 20
Create a typed variablevar age int = 20
Calculatetotal := price * quantity
Make a decisionif age >= 18 { ... }
Repeat instructionsfor i := 0; i < 5; i++ { ... }
Define a functionfunc add(a int, b int) int { return a + b }
Create a sliceprices := []int{10, 20, 30}
Create a mapprices := map[string]int{"Pen": 10}
Search textstrings.Contains(message, word)
Handle an error returned by a functionresult, err := someFunction() followed by an if err != nil check

Remember that someFunction() above is illustrative pseudocode, not a real Go function. Actual error handling depends on the function being called.

Final skill test — Can you program independently?

Try these questions without looking at the explanations above.

5-question knowledge check

5/5 answered

1. What is the output of `fmt.Println(4 + 6 * 2)`?

A. 20

B. 16

C. 14

D. 24

2. Which Go structure is suited to a list of product prices that can grow?

A. bool

B. string

C. slice

D. comment

3. Which statement increases the variable `count` by one?

A. count == 1

B. count++

C. count = true

D. count: string

4. What is the purpose of a function's `return` statement?

A. Repeat a loop

B. Create a folder

C. Send a result back to the caller and end that function call

D. Print text automatically

5. Which condition checks that a price is at least 100?

A. price < 100

B. price == 100 only

C. price >= 100

D. price = 100

Check my answers

Two debugging challenges

Challenge A: Fix this code so it compiles.

Go

package main

import "fmt"

func main() {
    age := 25
    fmt.Println("Age:", age
}

Challenge B: Find the logic error.

Go

price := 500
quantity := 3
total := price + quantity

The intended result is the total cost of three items. What needs to change?

Independent coding challenge

Modify the mini billing system to calculate the cost of three different products and print their combined subtotal.

Requirements:

  • Store the three product prices in a slice.

  • Use a loop to calculate their total.

  • Create a function to calculate a 10% discount.

  • Print the subtotal, discount, and final total.

Try it yourself before viewing the solution.

Reveal debugging answers

Hide answers

Challenge A: Add the missing closing parenthesis:

Go

fmt.Println("Age:", age)

Challenge B: Multiply the unit price by the quantity:

Go

total := price * quantity

Independent challenge: The solution should use a slice, a for loop, and a discount function. You should be able to explain why the loop visits every price and why the function returns the discount amount.

Your Block 1 target: You do not need to memorize every example. You should be able to read simple Go code, understand variables and conditions, write loops and functions, work with collections, and debug basic mistakes. Once you can do that with limited assistance, you are ready for Block 2: structs, packages, files, JSON, testing, and project organization.

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.