You signed in with another tab or window.Reload to refresh your session.You signed out in another tab or window.Reload to refresh your session.You switched accounts on another tab or window.Reload to refresh your session.Dismiss alert
# A for loop is used for iterating over a sequence (that is either a list, a tuple, a dctionary, a set, or a string).
6
+
# This is less like the for keyword in other programming language, and works more like an iterator method as found in other object-orientated programming languages.
7
+
# With the for loop we can execute a set of statements, once for each item in a list, tuple, set etc.
8
+
9
+
fruits= ["apple","banana","cherry"]
10
+
forxinfruits:
11
+
print(x)
12
+
13
+
# The for loop does not require an indexing variable to set beforehand.
14
+
15
+
#Loop Through a String
16
+
#
17
+
# Even strings are iterable objects, they contain a sequence of characters:
18
+
forxin"banana":
19
+
print(x)
20
+
21
+
fruits= ["apple","banana","cherry"]
22
+
forxinfruits:
23
+
print(x)
24
+
ifx=="banana":
25
+
break
26
+
27
+
fruits= ["apple","banana","cherry"]
28
+
forxinfruits:
29
+
ifx=="banana":
30
+
break
31
+
print(x)
32
+
33
+
# The continue Statement
34
+
fruits= ["apple","banana","cherry"]
35
+
forxinfruits:
36
+
ifx=="banana":
37
+
continue
38
+
print(x)
39
+
40
+
# The range() Function
41
+
#
42
+
# To loop through a set of code a specified number o fimtes, we can use the range() function,
43
+
# The range() function returns a sequence of numbers, starting from 0 by default, and increments by 1 (by default), and ends at a specified number.
44
+
45
+
forxinrange(6):
46
+
print(x)
47
+
48
+
# Note that range(6) is not the values of 0 to 6, but the values 0 to 5.
49
+
50
+
# The range() function defaults to 0 as a starting value, however it is possible to specify the starting value by addin a parameter:
51
+
# range(2, 6), which means values from 2 to 6 (but no including 6):
52
+
forxinrange(2,6):
53
+
print(x)
54
+
55
+
# The range() function defaults to increment the sequence by 1, however it is possible to specify the increment value by adding a third parameter: range(2, 30, 3):
56
+
forxinrange(2,30,3):
57
+
print(x)
58
+
59
+
# Else in For Loop
60
+
#
61
+
# The else keyword in a for loop specifies a block of code to be executed when the loop is finished:
62
+
63
+
# Print all numbers from 0 to 5, and print a message when the loop has ended:
64
+
forxinrange(6):
65
+
print(x)
66
+
else:
67
+
print("Finally finished!")
68
+
69
+
# Nested Loops
70
+
#
71
+
# A nested loop is a loop inside a loop.
72
+
# The "inner loop" will be executed one time for each iteration of the "outer loop":