How does a for loop work in Python?

The easiest way to understand what a for loop does is to see an example. Below is one of the simplest for loops you can make. Can you guess what the output might be? for i in [1,2,3,4,5]: print iThe output are the integers 1, 2, 3, 4, 5. Python is going through the for loop 5 times. At the start of the loop, i is set to the next number in the list. In the loop, i is printed. Now let's look at a more complicated example to check our understanding:for i in [2,4,6,8]: j = i*2 print j Can you tell me what the output will be? Answer 4, 8, 12, 16Can you explain the process, on each loop, what are i and j? Answer, first loop i = 2, j = 4. Second loop i = 4 j = 8...

TC
Answered by Toby C. Python tutor

1069 Views

See similar Python Mentoring tutors

Related Python Mentoring answers

All answers ▸

What would you expect to be the output of the following code snippet: `a = [1, 2, 3]; b = a; b[1] = 4; print(a); print(b);`, and why?


Why would I use dictionaries instead of a list?


Write a python function that takes a string as parameter and returns the character in the string with the most occurrences, along with the number of times this character occurs


Which function is ran when an object is instantiated?


We're here to help

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

© MyTutorWeb Ltd 2013–2025

Terms & Conditions|Privacy Policy
Cookie Preferences