Conditionals and Loops
This content is not available in your language yet.
If, Elif, and Else Statements
If statements allow you to create conditions for certain code to run. This can make your programs a lot more interesting and varied.
You can have multiple conditons before the else
. For every condition after the first you use elif
, short for else if.
Loops
Loops allow you repeat code over and over. There are 2 main types of loops, while
loops and for
loops.
A while
loop will continue repeating code until a certain condition is no longer met. To show a while
loop, we’re going to modify the number guessing game above. As it currently is, you can only guess once before the program ends. That’s boring. Using a while loop we can let the user continue guessing until they get it correct.
Now the program will continue asking the user to guess the number until they guess it correctly.
A for
loop lets you loop a set number of times, rather than until a condition is no longer met. Let’s create a for
loop that sums the numbers from 1 to 10.
Let’s break this down a bit. range
gives a sequence of numbers starting from 0 and ending before the given number. So in this case it gives the number sequence 0, 1, 2, 3, 4, 5, 6, 7, 8, 9
. num
is being assigned one of those numbers as it goes through the loop which can then be used inside the loop as a variables. The code is saying for each number in this sequence, assign it to the variable num
and then run the code inside the loop.
There are other ways to use range
. Notice how we had to add 1 to num
when summing the numbers, as they started at 0. We can avoid this by giving 2 numbers to range
.
This is saying to start the sequence with the number 1 and end the sequence right before the number 11.
You can also tell range
to jump numbers in a sequence. Let’s say you wanted to sum all the even numbers from 0 to 20.
This is saying to start the sequence at 0, end it just before 21, and skip every second number. The given sequence would then be 0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20
.