Skip to content

Commit d70ef56

Browse files
committed
python loops
1 parent 2fa0077 commit d70ef56

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed
+37
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
"""
2+
Python have two loops, while and for loop.
3+
4+
While loop is used when you don't know about the number of iterations.
5+
Example, you have to take input from user repeatedly until it enters correct input.
6+
7+
For loop is used when you know about the number of iterations.
8+
Example, print a number 10 times.
9+
10+
"""
11+
12+
n = 5
13+
while n < 5:
14+
print(n)
15+
n += 1
16+
17+
"""
18+
We use range function for iteration in for loop.
19+
Some facts about range function:
20+
1. By default, it starts with 0.
21+
2. range(stop_value) equals to i < stop_value. It means last digit is always exclusive.
22+
3. You can also specify the starting value like this => range(start, stop).
23+
4. By default, it increments by +1.
24+
5. You can also specify the incrementing value like this => range(start, stop, increment).
25+
"""
26+
27+
# Looping from i = 0 to i = 4
28+
for i in range(5):
29+
print(i)
30+
31+
# Looping from i = 2 to i = 5
32+
for i in range(2, 6):
33+
print(i)
34+
35+
# Looping from i = 5 to i = 2 with -1 increment
36+
for i in range(5, 1, -1):
37+
print(i)

0 commit comments

Comments
 (0)