Before you start this course, you must login to Replit
If you have forgotten your Replit account user name or password, ask your Coder Coach.
If you have forgotten your Replit account user name or password, ask your Coder Coach.
At the ‘predict’ & ‘run’ stages students work entirely with example code. They should inspect it carefully and write a prediction about what it will do.
They then run the code and compare the result to their prediction.
This unit is focused on iteration, the code that makes Python repeat certain lines of code. Iteration is often more commonly known as looping.
A loop repeats the code inside it. There are several different types of loop, but in this course we are going to learn about conditional, or while loops.
A while loop repeats the code inside it while the condition is True. When the computer gets to the start of the loop it checks the condition. If the condition is True Python enters the loop and runs the code inside it. If the condition is false, Python skips past the loop and carries on with the rest of the program.
When Python gets to the end of the loop it goes back and checks the condition again. If the condition is still True it goes back into the loop and runs the code inside again. This keeps happening until the condition changes to become False.
This code will repeat until the user input the correct answer:
print("What's the capital of France?")
answer = input()
while answer != "Paris":
print("Incorrect! Try again")
print("What's the capital of France?")
answer = input()
print("Congratulations!")
Looping is often used to validate input as can be seen in the above example. There are some key points to be aware of:
!=
)Make sure that you check for the following things:
while
while
line has a conditionwhile
line has a colon at the endwhile
.