|
| 1 | +# https://newdigitals.org/2024/01/23/basic-python-programming/#loops |
| 2 | +# Loops |
| 3 | +# A for loop is used for iterating over a sequence (that is either a list, a tuple, a dictionary, a set, or a string). Loop through the letters in the word "banana": |
| 4 | +for x in "banana": |
| 5 | + print(x) |
| 6 | +Output: |
| 7 | +b |
| 8 | +a |
| 9 | +n |
| 10 | +a |
| 11 | +n |
| 12 | +a |
| 13 | +#With the break statement we can stop the loop before it has looped through all the items: |
| 14 | +#Exit the loop when x is "banana" |
| 15 | +fruits = ["apple", "banana", "cherry"] |
| 16 | +for x in fruits: |
| 17 | + print(x) |
| 18 | + if x == "banana": |
| 19 | + break |
| 20 | + |
| 21 | +Output: |
| 22 | +apple |
| 23 | +banana |
| 24 | + |
| 25 | +#To loop through a set of code a specified number of times, we can use the range() function |
| 26 | + |
| 27 | +for x in range(6): |
| 28 | + print(x) |
| 29 | + |
| 30 | +Output: |
| 31 | +0 |
| 32 | +1 |
| 33 | +2 |
| 34 | +3 |
| 35 | +4 |
| 36 | +5 |
| 37 | +#The range() function defaults to increment the sequence by 1, however it is possible to specify the increment value by adding a third parameter: |
| 38 | +for x in range(2, 30, 3): |
| 39 | + print(x) |
| 40 | +Output: |
| 41 | +2 |
| 42 | +5 |
| 43 | +8 |
| 44 | +11 |
| 45 | +14 |
| 46 | +17 |
| 47 | +20 |
| 48 | +23 |
| 49 | +26 |
| 50 | +29 |
| 51 | + |
| 52 | +#A nested loop is a loop inside a loop. The "inner loop" will be executed one time for each iteration of the "outer loop": |
| 53 | +adj = ["red", "big", "tasty"] |
| 54 | +fruits = ["apple", "banana", "cherry"] |
| 55 | + |
| 56 | +for x in adj: |
| 57 | + for y in fruits: |
| 58 | + print(x, y) |
| 59 | +Output: |
| 60 | +red apple |
| 61 | +red banana |
| 62 | +red cherry |
| 63 | +big apple |
| 64 | +big banana |
| 65 | +big cherry |
| 66 | +tasty apple |
| 67 | +tasty banana |
| 68 | +tasty cherry |
| 69 | + |
| 70 | +#With the while loop we can execute a set of statements as long as a condition is true. Print i as long as i is less than 6: |
| 71 | +i = 1 |
| 72 | +while i < 6: |
| 73 | + print(i) |
| 74 | + i += 1 |
| 75 | +Output: |
| 76 | +1 |
| 77 | +2 |
| 78 | +3 |
| 79 | +4 |
| 80 | +5 |
0 commit comments