How do For Loops work?

For loops will execute certain statements within the loop for a specified number of runs. This is an example of a python programme:1 for i in range(5): 2  print(i) 3 else: 4  print('done') In this example, the output is: 0, 1, 2, 3, 4, done. We specified we want the loop to run whilst it is in the range 0 < i < 4 on the first line. It only goes up to 4 as it starts at 0 (in python, counters start at 0 but you can make them start at 1 by assigning 1 to the counter before the loop e.g. i = 1). For loops update the counter automatically, which means that 1 is added to i after every run without having to write i += 1 after line 2. Therefore we get 0, 1, 2, 3, 4 as outputs for the first 5 runs, but as i becomes i = 6 after the 5th run, it is no longer in the range and does not satisfy the condition of the loop, therefore it moves to the else condition. Here, it executes line 4 and we get the output 'done'.

Answered by Niusha S. Python tutor

1254 Views

See similar Python Mentoring tutors

Related Python Mentoring answers

All answers ▸

Write a simple number guessing game, give the user 3 tries to guess a number between 1 and 10


Write a function that takes a string, and outputs that string formatted in camelcase. (alternating upper and lower case for each character, e.g. cAmElCaSe)


What would output this code? print(hello world)


Firstly, my question is not Python related, but maths A-level related. I don't know how to change that in my profile but I would like to only tutor maths GCSE and potentially A-level. My question: Integrate sin(x)^3 over x=0 and x=pi/2.


We're here to help

contact us iconContact usWhatsapp logoMessage us on Whatsapptelephone icon+44 (0) 203 773 6020
Facebook logoInstagram logoLinkedIn logo
Cookie Preferences