Section 2 of 12

Control Flow & Functions

Master conditionals, loops, and function definitions

Course Progress

Section 2 of 12

17% complete

Tutorials

Conditionals

Conditionals allow you to execute different code based on conditions. ## If/Else Statements Go provides straightforward conditional statements without parentheses.

Code Examples

If/Elsego
package main

import "fmt"

func main() {
    age := 25
    
    if age >= 18 {
        fmt.Println("Adult")
    } else if age >= 13 {
        fmt.Println("Teenager")
    } else {
        fmt.Println("Child")
    }
    
    // Short statement in if
    if score := 85; score >= 80 {
        fmt.Println("Pass")
    }
}
Switch Statementgo
package main

import "fmt"

func main() {
    day := 3
    
    switch day {
    case 1:
        fmt.Println("Monday")
    case 2:
        fmt.Println("Tuesday")
    case 3:
        fmt.Println("Wednesday")
    default:
        fmt.Println("Other day")
    }
}

Loops

Go simplifies looping with a single for loop construct that handles all loop scenarios.

Code Examples

For Loop Variationsgo
package main

import "fmt"

func main() {
    // Traditional for loop
    for i := 0; i < 5; i++ {
        fmt.Println(i)
    }
    
    // While-like loop
    counter := 0
    for counter < 3 {
        fmt.Println(counter)
        counter++
    }
    
    // Infinite loop with break
    for {
        fmt.Println("Loop")
        break
    }
}
Range Loopgo
package main

import "fmt"

func main() {
    numbers := []int{10, 20, 30, 40}
    
    // Index and value
    for i, num := range numbers {
        fmt.Printf("Index: %d, Value: %d\n", i, num)
    }
    
    // Just values
    for _, num := range numbers {
        fmt.Println(num)
    }
    
    // String iteration
    str := "Hello"
    for i, char := range str {
        fmt.Printf("%d: %c\n", i, char)
    }
}

Functions

Functions are reusable blocks of code. Go emphasizes simplicity and clarity in function definition.

Code Examples

Function Basicsgo
package main

import "fmt"

// Basic function
func greet(name string) {
    fmt.Println("Hello, " + name)
}

// Function with return value
func add(a int, b int) int {
    return a + b
}

// Multiple return values
func divide(a, b float64) (float64, error) {
    if b == 0 {
        return 0, fmt.Errorf("division by zero")
    }
    return a / b, nil
}

func main() {
    greet("Alice")
    
    result := add(5, 3)
    fmt.Println(result)
    
    quotient, err := divide(10, 2)
    if err != nil {
        fmt.Println("Error:", err)
    } else {
        fmt.Println(quotient)
    }
}
Variadic Functionsgo
package main

import "fmt"

// Function accepting variable number of arguments
func sum(numbers ...int) int {
    total := 0
    for _, num := range numbers {
        total += num
    }
    return total
}

// Defer - runs after function returns
func demonstrate() {
    defer fmt.Println("Cleanup")
    fmt.Println("Main code")
}

func main() {
    fmt.Println(sum(1, 2, 3, 4, 5))
    demonstrate()
}

Exercises

Grade Calculator

Create a function that takes a score and returns a grade (A, B, C, D, F)

INTERMEDIATE

Starter Code:

package main

import "fmt"

func getGrade(score int) string {
    // TODO: Implement grade logic
    return ""
}

func main() {
    fmt.Println(getGrade(95))
    fmt.Println(getGrade(85))
    fmt.Println(getGrade(75))
}

Hands-on Project

Temperature Converter

Create functions to convert between Celsius, Fahrenheit, and Kelvin

INTERMEDIATE

Learning Objectives

  • >Write functions with parameters
  • >Handle multiple calculations
  • >Return multiple values

Project Tips

  • > Start by understanding the requirements
  • > Break the project into smaller tasks
  • > Test your code frequently as you build
  • > Add error handling throughout your code
  • > Consider edge cases and validate inputs
  • > Document your code with comments