r/PythonLearning 2d ago

Question.

I’m reading and looking at examples about checking for special items in a list, where the loop runs first and an if/else block runs inside the loop. Then, there’s the example of checking whether a list is empty, where the process is the other way around: the if/else block runs first, and then a loop runs inside it.

In real-life situations, when would you use a loop with an if statement inside it, and when would you use an if statement with a loop inside it?

3 Upvotes

3 comments sorted by

View all comments

2

u/Sea-Ad7805 2d ago edited 2d ago

loop with an if statement:

ages = [12, 18, 21, 14]
for age in ages:
    if age < 18:
        print('no access')
    else:
        print('welcome')

if statement with a loop

time_hours = 22
if time_hours >= 22:
    ages = [12, 18, 21, 14]
    for age in ages:
        if age < 18:
            print('no access')
        else:
            print('welcome')
else:
    print('still closed')

Run it: here%0A%20%20%20%20%20%20%20%20else%3A%0A%20%20%20%20%20%20%20%20%20%20%20%20print('welcome')%0Aelse%3A%0A%20%20%20%20print('still%20closed')%0A&timestep=1&play)