Python Code for nested loops
In python is there an easier way to write 6 nested for loops? - Stack Overflow
How to continue in nested loops in Python - Stack Overflow
[Python] Can someone please explain to me how nested for loops work using this example. I don't understand how it works
Videos
If you're frequently iterating over a Cartesian product like in your example, you might want to investigate Python 2.6's itertools.product -- or write your own if you're in an earlier Python.
from itertools import product
for y, x in product(range(3), repeat=2):
do_something()
for y1, x1 in product(range(3), repeat=2):
do_something_else()
This is fairly common when looping over multidimensional spaces. My solution is:
xy_grid = [(x, y) for x in range(3) for y in range(3)]
for x, y in xy_grid:
# do something
for x1, y1 in xy_grid:
# do something else
- Break from the inner loop (if there's nothing else after it)
- Put the outer loop's body in a function and return from the function
- Raise an exception and catch it at the outer level
- Set a flag, break from the inner loop and test it at an outer level.
- Refactor the code so you no longer have to do this.
I would go with 5 every time.
Here's a bunch of hacky ways to do it:
Create a local function
for a in b: def doWork(): for c in d: for e in f: if somecondition: return # <continue the for a in b loop?> doWork()A better option would be to move doWork somewhere else and pass its state as arguments.
Use an exception
class StopLookingForThings(Exception): pass for a in b: try: for c in d: for e in f: if somecondition: raise StopLookingForThings() except StopLookingForThings: pass
userInput = int(input())
for i in range(userInput):
for j in range(i,userInput):
print('*', end=' ')
print()input is: 3
the output is:
* * * * * * I have been looking at videos and different websites, but i cannot understand it.
Iโve been practicing for a week and trying to understand the grasp of how to type these codes myself. When I have them in front of me, it makes sense and I understand them. However, when it comes to actually writing them. I get stuck. Iโm a big visual learner so if anyone has tips on how they learned or who they learned from. Iโd appreciate it!