Respuesta :
Answer:
1. You do not know how many times a loop will need to run
4. To repeat code.
Explanation:
Required
When to use while loop instead of for loop?
Option 1 and 4 answer the question
1. You do not know how many times a loop will need to run
Using while loop in this case is suitable to the for loop.
Take for instance
You want a set of instruction to be repeated until the user enters 1
e.g.
while a != 1:
print("abc")
print("def")
a = int(input("Input: "))
The above is written in Python
The print instructions will be repeated until the user enter 1.
Now, you do not know if the user will enter 1 the first time or the 100th time or the 10000th time.
In other words, you don't know how many times the loop will be executed.
In this case, while loop is preferred to for loop
4. To repeat code:
The same analysis as used in (1) above is applicable in (4).
The print statements in
while a != 1:
print("abc")
print("def")
a = int(input("Input: "))
will be repeated until the user enters 1
The for loop isn't preferable in this case
Other options (2) and (3) can be implemented using both the for loops and the while loops
The while loops allows the execution of a block of code over and over again until a condition or certain conditions are met. The while lop are used instead of the for loop in the following circumstances :
- You do not know how many times a loop will need to run
- When using a count variable
Certain loops requires that a condition is met before the loop terminates. While some loops have a clear and predictable number of runs, some do not. Hence, due to this unpredictability, while loops are preferred :
Code snippet in python :
num = int(input())
while num < 5 :
print('invalid')
num = int(input())
Also, when using a count variable, the while loops is more appropriate as also more appropriate ;
Code snippet in python :
count = 20
while count > 0 :
print('available')
count -= 1
Therefore, the while loop is more appropriate for a loop with an unknown number of runs and when using the count variable.
Learn more :https://brainly.com/question/15745784
Otras preguntas
