Learn

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. With the argument of 100, the maximum value that the method will return is 99. Looking at the entire line fmt.Println(rand.Intn(100)), it should print a random integer from 0 to 99. 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. Use an argment of 10000 so that the maximum possible value generated is 9999.

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

Take this course for free

Mini Info Outline Icon
By signing up for Codecademy, you agree to Codecademy's Terms of Service & Privacy Policy.

Or sign up using:

Already have an account?