Python Basics
Loops in Python
for loop
Iterates over any iterable.
for ch in "abc":
print(ch)
for i in range(3): # 0, 1, 2
print(i)
while loop
n = 3
while n > 0:
print(n)
n -= 1
break, continue and else
for n in range(2, 10):
if n % 2 == 0:
continue # skip even numbers
if n > 7:
break # stop the loop
print(n)
else:
print("loop finished without break")
Useful helpers
names = ["Asha", "Ravi"]
for index, name in enumerate(names, start=1):
print(index, name)
for a, b in zip([1, 2], ["x", "y"]):
print(a, b)
Finished reading?
Mark it complete to track your progress across the docs.
Questions and discussion
Stuck on something here, or found a clearer way to explain it? Start a thread.
- Ask a question or share what helped
- React to useful answers
- Sign in with GitHub to post
Comments are stored in GitHub Discussions and shown here by giscus. PrepVerse never sees your GitHub password.