Describe both For-loops and While-loops and explain how you can simulate the effect of a for loop with a while loop with an example.

A while loop executes some code while a specific condition is true, once the condition is no longer true, the code skips the loop. It has the following form:while condition is true: do something A for loop is used to iterate through elements (for example, numbers in list) and perform some action for each iteration (for example, print the numbers to the screen). It has the following form:for element in list: do something An example use of a for loop is to iterate through a list of numbers to print the numbers. To print numbers 1-5 in Python would be done as follows:for i in range(1, 5): print(i) To replicate this with a While loop you could do the following:i = 0 while i < 5: i = i+1 print(i) Note the need to manually increase the counter, i, which is done automatically in the for loop

SC
Answered by Stephen C. Python tutor

1100 Views

See similar Python Mentoring tutors

Related Python Mentoring answers

All answers ▸

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.


How do I define a function in Python?


Write a recursive function to return the nth Fibonacci number in Python


How do I use format python code?


We're here to help

contact us iconContact ustelephone icon+44 (0) 203 773 6020
Facebook logoInstagram logoLinkedIn logo

© MyTutorWeb Ltd 2013–2025

Terms & Conditions|Privacy Policy
Cookie Preferences