Learn
Learn Go: Conditionals
Randomizing

Previously, we used hard coded values (values that don’t change) and then created conditionals that checked on these values. For example:

alarmRinging := true if alarmRinging { fmt.Println("Turn off the alarm!!") }

We knew that our condition would be true and the print statement would execute. This level of certainty is usually NOT the reason why we would use a conditional. Instead, we create conditionals to account for different conditions and different possible outcomes.

So let’s introduce some uncertainty to our code by generating a random number. Go has a math/rand library that helps us generate a random integer:

import ( "math/rand" "fmt" ) func main() { fmt.Println(rand.Intn(100)) }

In our main function, we’re printing out a random number using rand and the Intn() method. The argument, 100, is the maximum value that the method will return. Looking at the entire line fmt.Println(rand.Intn(100)), it should print a random integer from 0 to 100. However, if we run our program multiple times, we’ll find that it always prints 81.

We’ll figure out why this happens in the next exercise, for now let’s see rand.Intn() in action.

Instructions

1.

Use rand.Intn() to generate a new random integer for amountLeft. The maximum value we want to generate is 10000.

After passing this checkpoint, run your code a few times to see that amountLeft has the same value each time.

Folder Icon

Take this course for free

Already have an account?