Python Concepts/For Statement
Objective[edit | edit source]
|
Page Index[edit | edit source]
|
Lesson[edit | edit source]The For Statement[edit | edit source]Even 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 Statement[edit | edit source]Much 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 Statement[edit | edit source]The >>> 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 Statement[edit | edit source]The >>> 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 | edit source] |
Execution speed
[edit | edit source]
with range()[edit | edit source]When 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 |
Assignments[edit | edit source]
|
|
References
[edit | edit source]1.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: