replit

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.

CoderSports


10.7 – Modify

In the modify tasks, students adapt the example code to start to create code of their own.

Make sure that the students add comments to explain what the code does.


In this unit you will learn about: Iteration

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:

  • The user is asked a question and their response is stored in a variable.
  • A loop is started with a condition that can be explained as ‘while the user gets the answer wrong’ using the not equals operator (!=)
  • Code inside the loop is indented, just like if…else statements.
  • Inside the loop, the user is given an error message
  • Inside the loop the user is given another chance to input – this is essential! Missing this step means that the user never has a chance to change their answer therefore creating an infinite loop
  • Getting the answer right breaks the loop as the condition is no longer True. Python moves on to the code after the loop.

Help! My Code Does Not Work!

Make sure that you check for the following things:

  • Iteration begins with while
  • The while line has a condition
  • The while line has a colon at the end
  • All the code you want to repeat is indented after the while.
  • Any code that should run once the loop has finished is not indented

Hints