When do we use a for-loop and when a while-loop?

In general, a for-loop is used when the number of iterations is predefined, and a while-loop is used when the number of iterations is not known in advance. When a for-loop is used, a while-loop can also be used. In this case, we usually prefer using a for-loop, due to the simplicity of its syntax. One example where both types can be used is shown below.

Write a short program to print the numbers 1 to 10.
For-loop:
for i in range(1,10): print(i) While-loop:
i = 1 while (i <= 10): print(i) i += 1
However, this does not work the other way around. Here is an example, where only a while-loop can be used.

Write a short program to calculate the sum of the numbers that the user enters. The program terminates when the user enters a negative number.
While-loop:
message = “Please enter a number!” x = input(message) sum = 0 while(x >= 0): sum += x x = input(message)
There is no way that the above example can be implemented using a for-loop as we don’t know how many numbers the user will enter before entering a negative number. On top of that, every time that the program is executed a different amount of numbers will be entered depending on the situation.

Answered by EIina M. Python tutor

1265 Views

See similar Python Mentoring tutors

Related Python Mentoring answers

All answers ▸

With the help of Pandas and Numpy library create a DataFrame with the columns "Name", "Surname", "Age" and "Gender", create as many rows as you want. Print out the result.


What can I do with Python?


What is the outcome of the following code? print(2*[3,4,5])


Sales is real Customers is integer startmainprog input Sales input Customers if ((Sales > 500) OR ((Sales > 300) AND (Customers>9))) then output “Bonus Awarded” else output “No Bonus” end if end subroutine. Sales = 600 Customers = 9, answer:


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–2024

Terms & Conditions|Privacy Policy