Python Concepts/For Statement
Objectiveedit
|
Page Indexedit
|
LessoneditThe For StatementeditEven though the >>> for spam in ("A", "B", "C", "D", "..."):
... print(spam)
...
A
B
C
D
...
As you can see, the temporary variable that holds the item from a sequence or collection follows the The way >>> for orange in range(10):
... print(orange)
...
0
1
2
3
4
5
6
7
8
9
>>> for juice in range(2, 10):
... print(juice)
...
2
3
4
5
6
7
8
9
The The second example uses two parameters, the first is the number to start from, instead of a default 0. The second parameter is the number to stop. So like the example, A little follow up on the The Else StatementeditMuch like the >>> for blue in (1, 2, 3, 4, 5, 6, 7):
... print(blue % 2)
... else:
... print("The for loop was a success!")
...
1
0
1
0
1
0
1
The for loop was a success!
The Break StatementeditThe >>> for berry in (1, 2, 3, 4, 5, 6, 7, 8):
... print(berry % 4)
... if berry % 4 == 0:
... break
... else:
... print("The for loop didn't end prematurely!")
...
1
2
3
0
The Continue StatementeditThe >>> for eggs in (1, 2, 3, 4, 5, 6, 7, 8, 9, 10):
... if eggs % 2 == 0:
... continue
... print(eggs % 2)
...
1
1
1
1
1
|
Examples of
edit
|
Execution speed
edit
with range()editWhen limit = 100_000_000
condition = 2
print ('condition =', condition)
while (1) :
if (condition == 1) :
print ('testing "for"')
for count in range (0,limit) : pass
break
if (condition == 2) :
print ('testing "while"')
count = 0
while (count < limit) : count += 1
break
$ time python3.6 for.py ;echo $?
condition = 1
testing "for"
real 0m6.946s
user 0m6.919s
sys 0m0.016s
0
$ time python3.6 for.py ;echo $?
condition = 2
testing "while"
real 0m19.453s
user 0m19.416s
sys 0m0.023s
0
$
This example shows that the |
Assignmentsedit
|
|
References
edit1.WikiVersity:
Previous lesson "Dictionaries#An_elementary_database" for examples of for
loops.
2. Python's documentation:
"8.3. The for statement", "4.4. break and continue Statements, and else Clauses on Loops", "4.6.6. Ranges", "5.6. Looping Techniques", "7.9. The break statement", "7.10. The continue statement"
3. Python's methods:
4. Python's built-in functions: