Conditional statements tell a program to evaluate when certain conditions are met. A specific code evaluates if the set condition is met and if not, the program will continue to move down to evaluate other codes.
Conditional statements are part of every programming language. Some instances where they can be applied include;
- Grading students exam: If the student gets an overall score of 70 and above, the student gets an A. If it’s a score of 69 – 60, the grade is B, if the score lies between 59 – 50, it’s a C grade, and so on.
- Discount on sales: If a customer buys a large-sized pizza they get a 5% discount, a medium-size gets a 2% discount and a small size gets no discount.
This means we can implement decision-making ability in our programs using conditionals, as they check values and evaluate them depending on their status. If the value turns out to be true or false, the program executes an appropriate block of code in response.
Prerequisites
This article explains a fun project with Go programming language, yes, we are planning a heist! 🤑 To fully understand this article you need to have;
- Go setup on your computer.
- A basic understanding of the Go syntax, find a guide here.
- A text editor such as VS Code, Sublime etc., or a Go IDE.
Disclaimer: This article does not encourage any heist related activity, this is only a hypothetical fun project.
Source: codecademy
Package declaration and Imports
The first thing to do when starting any Go program is the package declaration, package main
. Packages are Go's way of organizing and reusing code and every Go program must start with a package declaration, find an insight into packages here. The next thing is to import the packages to be used in the program.
package main
import (
"fmt"
"math/rand"
"time"
)
- The
import
keyword is how we include code from other packages to use in a program. - The
fmt
package (fmt - format), implements formatting our input and output. - The
math/rand
package is used to generate random numbers. - The
time
package is used for measuring and displaying time.
These packages are surrounded by double quotes " "
, which is known as a string literal, a type of expression in Go.
Variable declaration
var heistOn bool = true
Here we are declaring a boolean variable heistOn
and setting its value to true. This value would keep track of how successful the heist is.
Seed value
Since this is more like a hypothetical simulator, we are going to generate random numbers to tackle the uncertainty that comes with planning a low budget bank heist 😂. To do that, there is a need for a unique seed value that generates a pseudo-random number, meaning a number that is not truly random as its value is determined by the initial value known as a seed.
Note: By default, the seed value is always 1, and using this means the same random numbers are generated each time, hence the need for the current time converted by UnixNano.
We are setting a seed value as the number of seconds which has elapsed since January 1, 1970, UTC (Unix time). This is also achieved with the time
package imported earlier so that we get a unique value each time the program is run, In the main function, call:
func main() {
rand.Seed(time.Now().UnixNano())
}
Functions are the building blocks of a Go program. They have inputs, outputs, and a series of steps called statements that are executed in order.
All functions start with the keyword func
followed by the name of the function, func main
in this case. They also have parameters surrounded by parentheses (), an optional return type e.g int
and a body surrounded by curly braces {}.
The function above has no parameter and doesn't return anything. The name main
is special because it is the function that gets called when you execute the program.
Conditionals
Avoiding security
Let’s say we have a 50% chance of making it past the bank security, we’re going to use conditionals to simulate this process. A lot of times, conditionals are used with comparison operators. To use such an operator, there are two values or operands with the comparison operator between them. This is evaluated by Go’s compiler which looks at the value on the left side, compares it to the value on the right, and decides on a true or false value. These operators include;
- == Equal to
- != Not equal to
- < Less than
- > Greater than
- <= Less than or equal to
- >= Greater than or equal to
func escapingGuards() {
eludedGuards := rand.Intn(100)
if eludedGuards >= 50 {
fmt.Println("You managed to make it past the guards. Good job, but this is only the first step.")
} else {
heistOn = false
fmt.Println("Oops! Plan a better disguise next time, failed heist!")
return
}
}
Here I created a new function; escapingGuards
. Inside the function block, a new variable eludedGuards
that generates random numbers from 0 - 99. The conditional starting with the if
statement checks if the random number generated is at least 50, then we managed to scale through the guards, else
it is a failed attempt.
Opening the vault
There are also other operators referred to as Logical operators that can be used to check multiple conditions at a time. They include;
- && And: When using the && operator, both conditions being compared must evaluate to
true
for the entire condition to execute as true. Otherwise, if either condition evaluates as false, the && condition will also evaluate to false and the code inside theif
block will not execute. - || Or: The || operator only requires one of the conditions to be true for the entire statement to evaluate to true.
- ! Not: The ! operator negates or reverses the value of a boolean, it takes a true value and pass back false or vice versa.
// This function checks if we can open the bank's vault
func vaultAccess() {
openedVault := rand.Intn(100)
// Let’s say that opening the vault is harder than
//sneaking past the guards and we only have a 30% chance
if heistOn == true && openedVault >= 70 {
fmt.Println("\nThe vault is open!")
fmt.Println("Grab and Go!!!")
// This accounts for failure
} else {
heistOn = false
fmt.Println("Sorry bro, this vault can't be opened")
}
}
Successful heist
We were able to scale through the security and opened the vault but that's not all, we still need to leave with the money without getting caught by any hidden camera, extra security, tripping an alarm, or anything else that might pose a hindrance.
func successfulOperation() {
leftSafely := rand.Intn(4)
if heistOn == true {
switch leftSafely {
case 0:
heistOn = false
fmt.Print("Looks like you tripped an alarm... run!!!")
case 1:
heistOn = false
fmt.Print("\nWe are trapped inside the vault, it doesn't open from inside...failed mission!!!")
case 2:
heistOn = false
fmt.Print("This is the Police freeze!")
default:
fmt.Println("\nWe've got the money...start the truck!")
amountStolen := 10000 + rand.Intn(1000000)
fmt.Print("We are $",amountStolen,"+ richer....hahaahah!!!")
}
}
}
In the code snippet above, a switch statement is used as an alternative syntax. It is simply a shorter way to write a sequence of if-else
statements. The switch
keyword initiates the statement and is followed by a value which is compared to the value after each case
until there is a match. The default statement will run when none of the cases match.
Going back to the main
function, now we have to call all other functions in the main
to enable the program run.
func main() {
rand.Seed(time.Now().UnixNano())
escapingGuards()
vaultAccess()
successfulOperation()
fmt.Println("\nThe Heist is:", heistOn) // This keeps track of our heist value
}
Find the complete code here and feel free to play around with this as much as you like. 😄