A program’s
control flow is the order in which the program’s code executes. The control flow of a Python program depends on conditional
statements, loops, and function calls.
Python has a lot of idiosyncrasies in its design of control statements. For example it does not implement classic C-style for loop.
Now, we finally take our first step into the code structures that weave data into programs. Our first example is this tiny
Python program that checks the value of the GLD against previous day value and prints an appropriate comment:
gld=179.12 old_gld=168.73
if gld > old_gld:
print("GLD is increasing!")
else:
print("GLD is decreasing!")
We need to save this program into a file example1.py and then run it in debugger using the command:
python -m pdb example1.py
NOTE: In Win 8 and 20 you can open the command prompt in a proper directory if you
navigate to it using File explorer and then use open command prompt from the menu.
The if and else lines are Python statements that check whether a condition is a
Boolean
True value, or can be evaluated as True. Remember, print()
is Python’s built-in function to print things, normally to your screen.
NOTE
If you’ve programmed in other languages, note that you don’t need parentheses for the if test. For example, don’t say
something such as if (disaster == True) (the equality operator == is described in a few paragraphs). You do
need the colon (:) at the end of conditional. If, like me, you forget to type the colon at times, Python will display an error message.
Each print() line is indented under its test. Typically 3 or 4 spaces indent is used. Python expects you to be consistent with code within a section — the lines need to be indented the same amount,
lined up on the left. The recommended style, called PEP-8, is to use four spaces. Don’t use tabs, or mix tabs and spaces; it
messes up the indent count. That's why using specialized editor like PyCharm is desirable.
You can have tests within tests, as many levels deep as needed:
In the preceding example, we tested for "greater then" by using the operator ">". Here are Python’s
comparison operators:
equality
==
inequality
!=
less than
<
less than or equal
<=
greater than
>
greater than or equal
>=
All comparisons return the Boolean values True or False. Let’s see how these all work, but first, assign a value
to gld:
Note that two equals signs (==) are used to test equality; remember, a single equals sign (=)
is what you use to assign a value to a variable.
If you need to make multiple comparisons at the same time, you use the logical (or
boolean) operators
and, or, and not to determine the final Boolean result.
>>> 5 < x and x < 10
True
As “Precedence” points out, the easiest way to avoid confusion about precedence is to add parentheses:
>>> (5 < x) and (x < 10)
True
Here are some other tests:
>>> 5 < x or x < 10
True
>>> 5 < x and x > 10
False
>>> 5 < x and not x > 10
True
If you’re and-ing multiple comparisons with one variable, Python lets you do this:
>>> 5 < x < 10
True
It’s the same as 5 < x and x < 10. You can also write longer comparisons:
>>> 5 < x < 10 < 999
True
What Is True?
What if the element we’re checking isn’t a boolean? What does Python consider True and False?
A false value doesn’t necessarily need to explicitly be a boolean False. For example, these are all considered
False:
boolean
False
null
None
zero integer
0
zero float
0.0
empty string
''
empty list
[]
empty tuple
()
empty dict
{}
empty set
set()
Anything else is considered True. Python programs use these definitions of “truthiness” and “falsiness” to check for
empty data structures as well as False conditions:
some_list = []
if some_list:
print("There's some data in the list some_list")
else:
print("Hey, the list some_list is empty!")
If what you’re testing is an expression rather than a simple variable, Python evaluates the expression and returns a boolean result.
So, if you type:
if color == "red":
Python evaluates color == "red". In our earlier example, we assigned the string "green" to
color,
so color == "red" is False, and Python moves on to the next test:
elif color == "green":
Do Multiple Comparisons with in
Suppose that you have a letter and want to know whether it’s a vowel. One way would be to write a long if statement:
letter = 'o'
if letter == 'a' or letter == 'e' or letter == 'i' or letter == 'o' or letter == 'u':
print(letter, 'is a vowel')
else:
print(letter, 'is not a vowel')
Whenever you need to make a lot of comparisons like that, separated by or, use Python’s membership operator
in, instead:
>>> vowels = 'aeiou'
>>> letter = 'o'
>>> letter in vowels
True
>>> if letter in vowels:
... print(letter, 'is a vowel')
...
o is a vowel
Here’s a preview of how to use in with some data types that you’ll read about in detail in the next few chapters:
>>> letter = 'o'
>>> vowel_set = {'a', 'e', 'i', 'o', 'u'}
>>> letter in vowel_set
True
>>> vowel_list = ['a', 'e', 'i', 'o', 'u']
>>> letter in vowel_list
True
>>> vowel_tuple = ('a', 'e', 'i', 'o', 'u')
>>> letter in vowel_tuple
True
>>> vowel_dict = {'a': 'apple', 'e': 'elephant',
... 'i': 'impala', 'o': 'ocelot', 'u': 'unicorn'}
>>> letter in vowel_dict
True
>>> vowel_string = "aeiou"
>>> letter in vowel_string
True
For the dictionary, in looks at the keys (the lefthand side of the :) instead of their values.
Python 3.8 implements the walrus operator ( C-style assignment expression), which looks like this:
name := expression
Slightly artificial but simple example (most commonly walrus is used when you search sub-string in the string and
want to preserve the starting position of this search)
my_list = [1,2,3,4,5]
if len(my_list) > 3:
print(f"The list is too long with {len(my_list)} elements")
In this case the walrus operator eliminates the need to call the len() function twice.
my_list = [1,2,3,4,5]
if (n := len(my_list)) > 3:
print(f"The list is too long with {n} elements")
The walrus also can be used with for and while loops
Python has a while statement which has the loop test at the beginning of the loop,
but there's no variant which has the test at the end. As a result, you commonly see code like
this:
# Read lines until a blank line is found
while 1:
line = sys.stdin.readline()
if line == "\n":
break
The while 1: ... if (condition): break idiom is often seen in Python code. The code
might be clearer if you could write:
# Read lines until a blank line is found
do:
line = sys.stdin.readline()
while line != "\n"
Adding this new control structure to Python would be pretty straightforward, though any
existing code that used "do" as a variable name would be broken by the introduction of a new
do keyword. PEP 315:
"Enhanced While Loop" is a detailed proposal for adding a do construct, but at
this point no ruling on it has been made.
The addition of iterators in Python 2.2 has made it possible to write many such loops by
using the for statement instead of while , an idiom that you might find
preferable.:
...You can use it to execute different blocks of code, depending on the variable value during runtime. Here's an example of a
switch statement in Java.
public static void switch_demo(String[] args) {
int month = 8;
String monthString;
switch (month) {
case 1: monthString = "January";
break;
case 2: monthString = "February";
break;
case 3: monthString = "March";
break;
case 4: monthString = "April";
break;
case 5: monthString = "May";
break;
case 6: monthString = "June";
break;
case 7: monthString = "July";
break;
case 8: monthString = "August";
break;
case 9: monthString = "September";
break;
case 10: monthString = "October";
break;
case 11: monthString = "November";
break;
case 12: monthString = "December";
break;
default: monthString = "Invalid month";
break;
}
System.out.println(monthString);
}
Here's how it works:
Compiler generates a jump table for switch case statement
The switch variable/expression is evaluated once
Switch statement looks up the evaluated variable/expression in the jump table and directly decides which code block to execute.
If no match is found, then the code under default case is executed
In the above example, depending on the value of variable month , a different message will be displayed in the standard
output. In this case, since the month=8, 'August' will be printed in standard output.
When Guido van Rossum developed Python, he wanted to create a "simple" programming language that bypassed the vulnerabilities
of other systems. Due to the simple syntax and sophisticated syntactic phrases, the language has become the standard for various
scientific applications such as machine learning. Switch statements
Although popular languages like Java and PHP have in-built switch statement, you may be surprised to know that Python language
doesn't have one. As such, you may be tempted to use a series of if-else-if blocks, using an if condition for each case of your switch
statement.
However, because of the jump table, a switch statement is much faster than an if-else-if ladder. Instead of evaluating each condition
sequentially, it only has to look up the evaluated variable/expression once and directly jump to the appropriate branch of code to
execute it.
The Pythonic way to implement switch statement is to use the powerful dictionary mappings, also known as associative arrays, that
provide simple one-to-one key-value mappings.
Here's the Python implementation of the above switch statement. In the following example, we create a dictionary named switcher
to store all the switch-like cases.
In the above example, when you pass an argument to the switch_demo function, it is looked up against the switcher
dictionary mapping. If a match is found, the associated value is printed, else a default string ('Invalid Month') is printed. The
default string helps implement the 'default case' of a switch statement.
Dictionary mapping for functions
Here's where it gets more interesting. The values of a Python dictionary can be of any data type. So you don't have to confine
yourself to using constants (integers, strings), you can also use function names and lambdas as values.
For example, you can also implement the above switch statement by creating a dictionary of function names as values. In this case,
switcher is a dictionary of function names, and not strings.
Although the above functions are quite simple and only return strings, you can use this approach to execute elaborate blocks of
code within each function.
Watch Now This tutorial has a related video course created by the Real Python team. Watch it together with the written tutorial
to deepen your understanding: For Loops in Python (Definite
Iteration)
This tutorial will show you how to perform definite iteration with a Python for loop.
In the previous tutorial in this introductory series,
you learned the following:
Repetitive execution of the same block of code over and over is referred to as iteration .
There are two types of iteration:
Definite iteration, in which the number of repetitions is specified explicitly in advance
Indefinite iteration, in which the code block executes until some condition is met
In Python, indefinite iteration is performed with a while loop.
Here's what you'll cover in this tutorial:
You'll start with a comparison of some different paradigms used by programming languages to implement definite iteration.
Then you will learn about iterables and iterators , two concepts that form the basis of definite iteration in Python.
Finally, you'll tie it all together and learn about Python's for loops.
Definite iteration loops are frequently referred to as for loops because for is the keyword that is
used to introduce them in nearly all programming languages, including Python.
Historically, programming languages have offered a few assorted flavors of for loop. These are briefly described
in the following sections.
Numeric Range Loop
The most basic for loop is a simple numeric range statement with start and end values. The exact format varies depending
on the language but typically looks something like this:
for i = 1 to 10
<loop body>
Here, the body of the loop is executed ten times. The variable i assumes the value 1 on the first iteration,
2 on the second, and so on. This sort of for loop is used in the languages BASIC, Algol, and Pascal.
Three-Expression Loop
Another form of for loop popularized by the C programming language contains three parts:
An initialization
An expression specifying an ending condition
An action to be performed at the end of each iteration.
This type of has the following form:
for (i = 1; i <= 10; i++)
<loop body>
Technical Note: In the C programming language, i++ increments the variable i . It is roughly equivalent
to i += 1 in Python.
This loop is interpreted as follows:
Initialize i to 1 .
Continue looping as long as i <= 10 .
Increment i by 1 after each loop iteration.
Three-expression for loops are popular because the expressions specified for the three parts can be nearly anything,
so this has quite a bit more flexibility than the simpler numeric range form shown above. These for loops are also featured
in the C++, Java, PHP, and Perl languages.
Collection-Based or Iterator-Based Loop
This type of loop iterates over a collection of objects, rather than specifying numeric values or conditions:
for i in <collection>
<loop body>
Each time through the loop, the variable i takes on the value of the next object in <collection> . This
type of for loop is arguably the most generalized and abstract. Perl and PHP also support this type of loop, but it
is introduced by the keyword foreach instead of for .
Further Reading: See the For loop Wikipedia page for an in-depth
look at the implementation of definite iteration across programming languages.
Remove ads The Python for
Loop
Of the loop types listed above, Python only implements the last: collection-based iteration. At first blush, that may seem like
a raw deal, but rest assured that Python's implementation of definite iteration is so versatile that you won't end up feeling cheated!
Shortly, you'll dig into the guts of Python's for loop in detail. But for now, let's start with a quick prototype
and example, just to get acquainted.
Python's for loop looks like this:
for <var> in <iterable>:
<statement(s)>
<iterable> is a collection of objects -- for example, a list or tuple. The <statement(s)> in the loop
body are denoted by indentation, as with all Python control structures, and are executed once for each item in <iterable>
. The loop variable <var> takes on the value of the next element in <iterable> each time through
the loop.
Here is a representative example:
>>>
>>> a = ['foo', 'bar', 'baz']
>>> for i in a:
... print(i)
...
foo
bar
baz
In this example, <iterable> is the list a , and <var> is the variable i .
Each time through the loop, i takes on a successive item in a , so print() displays the values
'foo' , 'bar' , and 'baz' , respectively. A for loop like this is the Pythonic
way to process the items in an iterable.
But what exactly is an iterable? Before examining for loops further, it will be beneficial to delve more deeply into
what iterables are in Python.
Iterables
In Python, iterable means an object can be used in iteration. The term is used as:
An adjective: An object may be described as iterable.
A noun: An object may be characterized as an iterable.
If an object is iterable, it can be passed to the built-in Python function iter() , which returns something called
an iterator . Yes, the terminology gets a bit repetitive. Hang in there. It all works out in the end.
Each of the objects in the following example is an iterable and returns some type of iterator when passed to iter()
:
>>>
>>> iter('foobar') # String
<str_iterator object at 0x036E2750>
>>> iter(['foo', 'bar', 'baz']) # List
<list_iterator object at 0x036E27D0>
>>> iter(('foo', 'bar', 'baz')) # Tuple
<tuple_iterator object at 0x036E27F0>
>>> iter({'foo', 'bar', 'baz'}) # Set
<set_iterator object at 0x036DEA08>
>>> iter({'foo': 1, 'bar': 2, 'baz': 3}) # Dict
<dict_keyiterator object at 0x036DD990>
These object types, on the other hand, aren't iterable:
>>>
>>> iter(42) # Integer
Traceback (most recent call last):
File "<pyshell#26>", line 1, in <module>
iter(42)
TypeError: 'int' object is not iterable
>>> iter(3.1) # Float
Traceback (most recent call last):
File "<pyshell#27>", line 1, in <module>
iter(3.1)
TypeError: 'float' object is not iterable
>>> iter(len) # Built-in function
Traceback (most recent call last):
File "<pyshell#28>", line 1, in <module>
iter(len)
TypeError: 'builtin_function_or_method' object is not iterable
All the data types you have encountered so far that are collection or container types are iterable. These include the
string ,
list ,
tuple ,
dict ,
set , and
frozenset types.
But these are by no means the only types that you can iterate over. Many objects that are built into Python or defined in modules
are designed to be iterable. For example, open files in Python are iterable. As you will see soon in the tutorial on file I/O, iterating
over an open file object reads data from the file.
In fact, almost any object in Python can be made iterable. Even user-defined objects can be designed in such a way that they can
be iterated over. (You will find out how that is done in the upcoming article on object-oriented programming.)
Okay, now you know what it means for an object to be iterable, and you know how to use iter() to obtain an iterator
from it. Once you've got an iterator, what can you do with it?
An iterator is essentially a value producer that yields successive values from its associated iterable object. The built-in function
next() is used to obtain the next value from in iterator.
In this example, a is an iterable list and itr is the associated iterator, obtained with iter()
. Each next(itr) call obtains the next value from itr .
Notice how an iterator retains its state internally. It knows which values have been obtained already, so when you call
next() , it knows what value to return next.
What happens when the iterator runs out of values? Let's make one more next() call on the iterator above:
>>>
>>> next(itr)
Traceback (most recent call last):
File "<pyshell#10>", line 1, in <module>
next(itr)
StopIteration
If all the values from an iterator have been returned already, a subsequent next() call raises a StopIteration
exception. Any further attempts to obtain values from the iterator will fail.
You can only obtain values from an iterator in one direction. You can't go backward. There is no prev() function.
But you can define two independent iterators on the same iterable object:
Even when iterator itr1 is already at the end of the list, itr2 is still at the beginning. Each iterator
maintains its own internal state, independent of the other.
If you want to grab all the values from an iterator at once, you can use the built-in list() function. Among other
possible uses, list() takes an iterator as its argument, and returns a list consisting of all the values that the iterator
yielded:
It isn't necessarily advised to make a habit of this. Part of the elegance of iterators is that they are "lazy." That means that
when you create an iterator, it doesn't generate all the items it can yield just then. It waits until you ask for them with
next() . Items are not created until they are requested.
When you use list() , tuple() , or the like, you are forcing the iterator to generate all its values
at once, so they can all be returned. If the total number of objects the iterator returns is very large, that may take a long time.
In fact, it is possible to create an iterator in Python that returns an endless series of objects. (You will learn how to do this
in upcoming tutorials on generator functions and itertools .) If you try to grab all the values at once from an endless
iterator, the program will hang .
You now have been introduced to all the concepts you need to fully understand how Python's for loop works. Before
proceeding, let's review the relevant terms:
Term
Meaning
Iteration
The process of looping through the objects or items in a collection
Iterable
An object (or the adjective used to describe an object) that can be iterated over
Iterator
The object that produces successive items or values from its associated iterable
iter()
The built-in function used to obtain an iterator from an iterable
Now, consider again the simple for loop presented at the start of this tutorial:
>>>
>>> a = ['foo', 'bar', 'baz']
>>> for i in a:
... print(i)
...
foo
bar
baz
This loop can be described entirely in terms of the concepts you have just learned about. To carry out the iteration this
for loop describes, Python does the following:
Calls iter() to obtain an iterator for a
Calls next() repeatedly to obtain each item from the iterator in turn
Terminates the loop when next() raises the StopIteration exception
The loop body is executed once for each item next() returns, with loop variable i set to the given item
for each iteration.
This sequence of events is summarized in the following diagram:
Schematic Diagram of a Python
for Loop
Perhaps this seems like a lot of unnecessary monkey business, but the benefit is substantial. Python treats looping over all iterables
in exactly this way, and in Python, iterables and iterators abound:
Many built-in and library objects are iterable.
There is a Standard Library module called itertools containing many functions that return iterables.
User-defined objects created with Python's object-oriented capability can be made to be iterable.
Python features a construct called a generator that allows you to create your own iterator in a simple, straightforward way.
You will discover more about all the above throughout this series. They can all be the target of a for loop, and
the syntax is the same across the board. It's elegant in its simplicity and eminently versatile.
Iterating Through a Dictionary
You saw earlier that an iterator can be obtained from a dictionary with iter() , so you know dictionaries must be
iterable. What happens when you loop through a dictionary? Let's see:
>>>
>>> d = {'foo': 1, 'bar': 2, 'baz': 3}
>>> for k in d:
... print(k)
...
foo
bar
baz
As you can see, when a for loop iterates through a dictionary, the loop variable is assigned to the dictionary's
keys.
To access the dictionary values within the loop, you can make a dictionary reference using the key as usual:
>>>
>>> for k in d:
... print(d[k])
...
1
2
3
You can also iterate through a dictionary's values directly by using .values() :
>>>
>>> for v in d.values():
... print(v)
...
1
2
3
In fact, you can iterate through both the keys and values of a dictionary simultaneously. That is because the loop variable of
a for loop isn't limited to just a single variable. It can also be a tuple, in which case the assignments are made from
the items in the iterable using packing and unpacking, just as with an assignment statement:
>>>
>>> i, j = (1, 2)
>>> print(i, j)
1 2
>>> for i, j in [(1, 2), (3, 4), (5, 6)]:
... print(i, j)
...
1 2
3 4
5 6
As noted in the tutorial on Python
dictionaries , the dictionary method .items() effectively returns a list of key/value pairs as tuples:
In the first section of this tutorial, you saw a type of for loop called a
numeric range loop , in which starting and
ending numeric values are specified. Although this form of for loop isn't directly built into Python, it is easily arrived
at.
For example, if you wanted to iterate through the values from 0 to 4 , you could simply do this:
>>>
>>> for n in (0, 1, 2, 3, 4):
... print(n)
...
0
1
2
3
4
This solution isn't too bad when there are just a few numbers. But if the number range were much larger, it would become tedious
pretty quickly.
Happily, Python provides a better option -- the built-in range() function, which returns an iterable that yields
a sequence of integers.
range(<end>) returns an iterable that yields integers starting with 0 , up to but not including
<end> :
>>>
>>> x = range(5)
>>> x
range(0, 5)
>>> type(x)
<class 'range'>
Note that range() returns an object of class range , not a list or tuple of the values. Because a
range object is an iterable, you can obtain the values by iterating over them with a for loop:
>>>
>>> for n in x:
... print(n)
...
0
1
2
3
4
You could also snag all the values at once with list() or tuple() . In a REPL session, that can be a
convenient way to quickly display what the values are:
However, when range() is used in code that is part of a larger application, it is typically considered poor practice
to use list() or tuple() in this way. Like iterators, range objects are lazy -- the values
in the specified range are not generated until they are requested. Using list() or tuple() on a range
object forces all the values to be returned at once. This is rarely necessary, and if the list is long, it can waste time
and memory.
range(<begin>, <end>, <stride>) returns an iterable that yields integers starting with <begin> , up
to but not including <end> . If specified, <stride> indicates an amount to skip between values (analogous
to the stride value used for string and list slicing):
All the parameters specified to range() must be integers, but any of them can be negative. Naturally, if <begin>
is greater than <end> , <stride> must be negative (if you want any results):
Technical Note: Strictly speaking, range() isn't exactly a built-in function. It is implemented as a callable class
that creates an immutable sequence type. But for practical purposes, it behaves like a built-in function.
You saw in the previous tutorial in this introductory series how execution of a while loop can be interrupted with
break and continue
statements and modified with an else clause . These capabilities are available with the for loop as well.
The break and continue Statements
break and continue work the same way with for loops as with while loops.
break terminates the loop completely and proceeds to the first statement following the loop:
>>>
>>> for i in ['foo', 'bar', 'baz', 'qux']:
... if 'b' in i:
... break
... print(i)
...
foo
continue terminates the current iteration and proceeds to the next iteration:
>>>
>>> for i in ['foo', 'bar', 'baz', 'qux']:
... if 'b' in i:
... continue
... print(i)
...
foo
qux
The else Clause
A for loop can have an else clause as well. The interpretation is analogous to that of a while
loop. The else clause will be executed if the loop terminates through exhaustion of the iterable:
>>>
>>> for i in ['foo', 'bar', 'baz', 'qux']:
... print(i)
... else:
... print('Done.') # Will execute
...
foo
bar
baz
qux
Done.
The else clause won't be executed if the list is broken out of with a break statement:
>>>
>>> for i in ['foo', 'bar', 'baz', 'qux']:
... if i == 'bar':
... break
... print(i)
... else:
... print('Done.') # Will not execute
...
foo
Conclusion
This tutorial presented the for loop, the workhorse of definite iteration in Python.
You also learned about the inner workings of iterables and iterators , two important object types that underlie definite iteration,
but also figure prominently in a wide variety of other Python code.
In the next two tutorials in this introductory series, you will shift gears a little and explore how Python programs can interact
with the user via input from the keyboard and output to the console.
All those languages essentially copied it from the granddaddy (i.e., C). Also, the ternary operator (properly called "conditional
expressions") are a relatively recent addition to Python (2.5) and from what I heard Guido resisted adding it.
And the BDFL also didn't copy other C features, e.g., increment/decrement operators, || and && for Boolean operations, switch/case
statements, and not least: BRACES!!! (for scope, of course).
To be fair, I find the inconsistency to be a little jarring too. While a lot of python flows nicely this jars; and working across
multiple languages is one of those oddities you need to remember for apparently no good reason.
The Last but not LeastTechnology is dominated by
two types of people: those who understand what they do not manage and those who manage what they do not understand ~Archibald Putt.
Ph.D
FAIR USE NOTICEThis site contains
copyrighted material the use of which has not always been specifically
authorized by the copyright owner. We are making such material available
to advance understanding of computer science, IT technology, economic, scientific, and social
issues. We believe this constitutes a 'fair use' of any such
copyrighted material as provided by section 107 of the US Copyright Law according to which
such material can be distributed without profit exclusively for research and educational purposes.
This is a Spartan WHYFF (We Help You For Free)
site written by people for whom English is not a native language. Grammar and spelling errors should
be expected. The site contain some broken links as it develops like a living tree...
You can use PayPal to to buy a cup of coffee for authors
of this site
Disclaimer:
The statements, views and opinions presented on this web page are those of the author (or
referenced source) and are
not endorsed by, nor do they necessarily reflect, the opinions of the Softpanorama society.We do not warrant the correctness
of the information provided or its fitness for any purpose. The site uses AdSense so you need to be aware of Google privacy policy. You you do not want to be
tracked by Google please disable Javascript for this site. This site is perfectly usable without
Javascript.