Python Tutorials - Herong's Tutorial Examples - v2.14, by Herong Yang
"for" Statement for Iterative Execution
This section provides a quick introduction of 'for' statement, which executes a block of sub-statements repeatedly while the given condition is valid.
What Is "for" Statement? A "for" statement is a compound statement that iterates over the elements of a sequence and executes a block of sub-statements for each iteration.
A "for" statements must have a "for" clause followed by an optional "else" clause:
for target in iterable: sub-statement sub-statement ... else: sub-statement sub-statement ...
Logically, you can replace a "for" statement with the following code using a "while" statement:
iter = iter(iterable) target = iter.__next__() while target: sub-statement sub-statement ... target = iter.__next__() else: sub-statement sub-statement ...
Two special statements can be used the sub-statement block:
Here is a Python sample code, for_test.py, that shows you how to use "for" statements.
# for_test.py #- Copyright 2011 (c) HerongYang.com. All Rights Reserved. # upperLimit = 20 for i in range(3, upperLimit): isPrime = True for j in range(2, 1+i//2): isPrime = i%j > 0 if not isPrime: break if isPrime: print(" "+str(i)+" is a prime number.") print("Reached the upper limit "+str(upperLimit))
If you run this sample code, you should get:
herong$ python for_test.py 3 is a prime number. 5 is a prime number. 7 is a prime number. 11 is a prime number. 13 is a prime number. 17 is a prime number. 19 is a prime number. Reached the upper limit 20
Notice that the range() function returns a "range" object. But it implements the "iterable" interface, so it is considered as an "iterable" object.
You can use the iter(object) function to check if an object is "iterable" or not. For example:
>>> iter(range(0,10)) <range_iterator object at 0x1095a1240> >>> iter([9,1,1]) <list_iterator object at 0x109264160> >>> iter((9,1,1)) <tuple_iterator object at 0x1095a18e0> >>> iter('911') <str_iterator object at 0x109264160> >>> iter(911) TypeError: 'int' object is not iterable
Table of Contents
Variables, Operations and Expressions
"pass" Statement - Do Nothing Statement
Expression Statement - One Expression Only
"=" Statement - Assignment Statement
"del" Statement - Delete Statement
"import" Statement to Load Modules
"if" Statement for Conditional Execution
"while" Statement for Execution Loop
►"for" Statement for Iterative Execution
"try" Statement to Catch Execution
"with" Statement for Context Manager
"match" Statement for Pattern Match
Function Statement and Function Call
Iterators, Generators and List Comprehensions
Packages and Package Directories
"pathlib" - Object-Oriented Filesystem Paths
"pip" - Package Installer for Python
SciPy.org - Python Libraries for Science
pandas - Data Analysis and Manipulation
Anaconda - Python Environment Manager