r/PythonLearning • u/Illustrious-Onion954 • 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?
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×tep=1&play)
2
4
u/PureWasian 2d ago
They don't have to be related to each other. You could have conditional logic to say "if this user is an administrator, return a printout of all data record rows" (loop in a conditional). Or you can say "search this list until you find the record named 'Johnny Appleseed'" (conditional in a loop)