Which statement is used to exit a loop prematurely in Python?a)nextb)b...
Explanation:
The correct statement used to exit a loop prematurely in Python is the break statement.
Break Statement:
The break statement is used to exit or terminate a loop prematurely. When the break statement is encountered inside a loop, the loop is immediately terminated, and the program execution continues with the next statement after the loop.
Usage:
The break statement can be used with the following loop structures in Python:
- for loop
- while loop
Example:
Let's consider an example where we want to print numbers from 1 to 5, but exit the loop if the number 3 is encountered. We can achieve this using the break statement as follows:
```
for i in range(1, 6):
print(i)
if i == 3:
break
```
Explanation of the Example:
- The for loop is used to iterate over the numbers from 1 to 5 (inclusive).
- Inside the loop, we print the current value of the variable i.
- We check if the value of i is equal to 3 using the if statement.
- If the condition is true, we encounter the break statement, which terminates the loop immediately.
- As a result, the program execution continues with the next statement after the loop.
Output:
The above example will output the following:
```
1
2
3
```
Conclusion:
The break statement is used to exit a loop prematurely in Python. It is useful when we want to terminate a loop based on a certain condition.
Which statement is used to exit a loop prematurely in Python?a)nextb)b...
The break statement is used to exit a loop prematurely. When encountered, it terminates the loop and transfers control to the statement immediately following the loop.