Pythonforloop
Pythonforloop
factorial=1
if num < 0:
print("must be positive")
elif num == 0:
print("1")
else:
factorial = factorial * i
print(factorial)
With the break statement we can stop the loop before it has looped through all
the items:
for x in fruits:
print(x)
if x == "banana":
break
fruits = ["apple", "banana", "cherry"]
for x in fruits:
if x == "banana":
break
print(x)
With the continue statement we can stop the current iteration of the loop, and continue with the next:
for x in fruits:
if x == "banana":
continue
print(x)
for x in range(6):
print(x)
print(x)
print(x)
Nested Loops
The "inner loop" will be executed one time for each iteration of the "outer loop":
Example
for x in adj:
for y in fruits:
print(x, y)
# List of numbers
sum = 0
sum = sum+val