May the source be with you, but remember the KISS principle ;-)
Home Switchboard Unix Administration Red Hat TCP/IP Networks Neoliberalism Toxic Managers
(slightly skeptical) Educational society promoting "Back to basics" movement against IT overcomplexity and  bastardization of classic Unix

Python Control Flow Statements

News  Python -- Scripting language with generators and coroutines.

Best Python books for system administrators

Recommended Links The if Statement  Loops in Python The Meaning of True and False in
Comparisons The Meaning of True and False in The assert Statement Generators Command-Line Syntax and Options Imitation of Perl double quoted strings in Python Chomp to string.rstrip

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.

Compare with if, elif, and else

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!")
    print("GLD is decreasing!")

We need to save this program into a file and then run it in debugger using the command:

python -m pdb

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.


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:

>>> gld=179.12

Now, letís try some tests:

>>> gld == 0
>>> gld == 179.12
>>> gld <= 180

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

As ďPrecedenceĒ points out, the easiest way to avoid confusion about precedence is to add parentheses:

>>> (5 < x) and (x < 10)

Here are some other tests:

>>> 5 < x or x < 10
>>> 5 < x and x > 10
>>> 5 < x and not x > 10

If youíre and-ing multiple comparisons with one variable, Python lets you do this:

>>> 5 < x < 10

Itís the same as 5 < x and x < 10. You can also write longer comparisons:

>>> 5 < x < 10 < 999

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")
   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')
 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
>>> 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
>>> vowel_list = ['a', 'e', 'i', 'o', 'u']
>>> letter in vowel_list
>>> vowel_tuple = ('a', 'e', 'i', 'o', 'u')
>>> letter in vowel_tuple
>>> vowel_dict = {'a': 'apple', 'e': 'elephant',
...               'i': 'impala', 'o': 'ocelot', 'u': 'unicorn'}
>>> letter in vowel_dict
>>> vowel_string = "aeiou"
>>> letter in vowel_string

For the dictionary, in  looks at the keys (the lefthand side of the :) instead of their values.

Python 3.8 introduced C-style operator := ( assignment expression or Walrus)

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

Top Visited
Past week
Past month


Old News ;-)

[Nov 21, 2019] No do statement

Nov 21, 2019 |

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": 

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
    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.:

for line in sys.stdin:
    if line == '\n':

[Nov 14, 2019] How to implement a switch-case statement in Python by Sreeram Sceenivasan

Oct 24, 2017 |

...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";
            case 2:  monthString = "February";
            case 3:  monthString = "March";
            case 4:  monthString = "April";
            case 5:  monthString = "May";
            case 6:  monthString = "June";
            case 7:  monthString = "July";
            case 8:  monthString = "August";
            case 9:  monthString = "September";
            case 10: monthString = "October";
            case 11: monthString = "November";
            case 12: monthString = "December";
            default: monthString = "Invalid month";

Here's how it works:

  1. Compiler generates a jump table for switch case statement
  2. The switch variable/expression is evaluated once
  3. Switch statement looks up the evaluated variable/expression in the jump table and directly decides which code block to execute.
  4. 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.

Read also: An introduction to the Python programming language

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.

SEE MORE: Python jumps past Java, Javascript is still most popular language for GitHubbers

How to implement switch statement in Python

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.

def switch_demo(argument):
switcher = {
  1: "January",
  2: "February",
  3: "March",
  4: "April",
  5: "May",
  6: "June",
  7: "July",
  8: "August",
  9: "September",
  10: "October",
  11: "November",
  12: "December"
print switcher.get(argument, "Invalid month")

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.

def one():
    return "January"
def two():
    return "February"
def three():
    return "March"
def four():
    return "April"
def five():
    return "May"
def six():
    return "June"
def seven():
    return "July"
def eight():
    return "August"
def nine():
    return "September"
def ten():
    return "October"
def eleven():
    return "November"
def twelve():
    return "December"
def numbers_to_months(argument):
    switcher = {
        1: one,
        2: two,
        3: three,
        4: four,
        5: five,
        6: six,
        7: seven,
        8: eight,
        9: nine,
        10: ten,
        11: eleven,
        12: twelve
    # Get the function from switcher dictionary
    func = switcher.get(argument, lambda: "Invalid month")
    # Execute the function
    print func()

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.

... ... ...

[Nov 13, 2019] Python for Loops (Definite Iteration) by John Sturtz

Jan 30, 2019 |

9 Comments basics python
Tweet Share Email

Table of Contents

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:

Here's what you'll cover in this tutorial:

Free Bonus: Click here to get access to a chapter from Python Tricks: The Book that shows you Python's best practices with simple examples you can apply instantly to write more beautiful + Pythonic code. Remove ads

A Survey of Definite Iteration in Programming

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:

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:

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>:

<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)

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.


In Python, iterable means an object can be used in iteration. The term is used as:

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>
TypeError: 'int' object is not iterable

>>> iter(3.1)                                  # Float
Traceback (most recent call last):
  File "<pyshell#27>", line 1, in <module>
TypeError: 'float' object is not iterable

>>> iter(len)                                  # Built-in function
Traceback (most recent call last):
  File "<pyshell#28>", line 1, in <module>
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.)

Remove ads Iterators

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.

Here is an example using the same list as above:

>>> a = ['foo', 'bar', 'baz']

>>> itr = iter(a)
>>> itr
<list_iterator object at 0x031EFD10>

>>> next(itr)
>>> next(itr)
>>> next(itr)

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>

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:

>>> a
['foo', 'bar', 'baz']

>>> itr1 = iter(a)
>>> itr2 = iter(a)

>>> next(itr1)
>>> next(itr1)
>>> next(itr1)

>>> next(itr2)

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:

>>> a = ['foo', 'bar', 'baz']
>>> itr = iter(a)
>>> list(itr)
['foo', 'bar', 'baz']

Similarly, the built-in tuple() and set() functions return a tuple and a set, respectively, from all the values an iterator yields:

>>> a = ['foo', 'bar', 'baz']

>>> itr = iter(a)
>>> tuple(itr)
('foo', 'bar', 'baz')

>>> itr = iter(a)
>>> set(itr)
{'baz', 'foo', 'bar'}

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 .

Remove ads The Guts of the Python for Loop

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)

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:

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:

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)

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])

You can also iterate through a dictionary's values directly by using .values() :

>>> for v in d.values():
...     print(v)

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:

>>> d = {'foo': 1, 'bar': 2, 'baz': 3}

>>> d.items()
dict_items([('foo', 1), ('bar', 2), ('baz', 3)])

Thus, the Pythonic way to iterate through a dictionary accessing both the keys and values looks like this:

>>> d = {'foo': 1, 'bar': 2, 'baz': 3}
>>> for k, v in d.items():
...     print('k =', k, ', v =', v)
k = foo , v = 1
k = bar , v = 2
k = baz , v = 3
Remove ads The range() Function

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)

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)

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:

>>> list(x)
[0, 1, 2, 3, 4]

>>> tuple(x)
(0, 1, 2, 3, 4)

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):

>>> list(range(5, 20, 3))
[5, 8, 11, 14, 17]

If <stride> is omitted, it defaults to 1 :

>>> list(range(5, 10, 1))
[5, 6, 7, 8, 9]
>>> list(range(5, 10))
[5, 6, 7, 8, 9]

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):

>>> list(range(-5, 5))
[-5, -4, -3, -2, -1, 0, 1, 2, 3, 4]

>>> list(range(5, -5))
>>> list(range(5, -5, -1))
[5, 4, 3, 2, 1, 0, -1, -2, -3, -4]
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.

For more information on range() , see the Real Python article Python's range() Function (Guide) . Remove ads Altering for Loop Behavior

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)

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)
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

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

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.

[Nov 13, 2019] I m annoyed with Python s ternary operator by Brian

Notable quotes:
"... THIS IS LAME!!! ..."
Jul 02, 2013 |


The ternary operator is a way to concisely say:
"If test , then a , else b ",

with the value of the statement being the value of a or b .

language how to say it
C test ? a : b
C++ test ? a : b
javaScript test ? a : b
Perl (not perl 6) test ? a : b
PHP test ? a : b
Ruby test ? a : b
Julia test ? a : b
Did I forget some language? probably
Python a if test else b


Ok. Now that I've written this post, I'll remember it.

However, I just want to say on behalf of all of the other multiple-language programmers in the world, THIS IS LAME!!!

Joe , July 2, 2013 at 4:11 pm

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).

Craig , July 2, 2013 at 7:16 pm

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.

[Nov 12, 2019] c - python (conditional-ternary) operator for assignments

Jul 30, 2014 |
This question already has an answer here:

karadoc ,May 14, 2013 at 13:01

Python has such an operator:
variable = something if condition else something_else

Alternatively, although not recommended (see @karadoc's comment):

variable = (condition and something) or something_else

Recommended Links

Google matched content

Softpanorama Recommended

Top articles




Groupthink : Two Party System as Polyarchy : Corruption of Regulators : Bureaucracies : Understanding Micromanagers and Control Freaks : Toxic Managers :   Harvard Mafia : Diplomatic Communication : Surviving a Bad Performance Review : Insufficient Retirement Funds as Immanent Problem of Neoliberal Regime : PseudoScience : Who Rules America : Neoliberalism  : The Iron Law of Oligarchy : Libertarian Philosophy


War and Peace : Skeptical Finance : John Kenneth Galbraith :Talleyrand : Oscar Wilde : Otto Von Bismarck : Keynes : George Carlin : Skeptics : Propaganda  : SE quotes : Language Design and Programming Quotes : Random IT-related quotesSomerset Maugham : Marcus Aurelius : Kurt Vonnegut : Eric Hoffer : Winston Churchill : Napoleon Bonaparte : Ambrose BierceBernard Shaw : Mark Twain Quotes


Vol 25, No.12 (December, 2013) Rational Fools vs. Efficient Crooks The efficient markets hypothesis : Political Skeptic Bulletin, 2013 : Unemployment Bulletin, 2010 :  Vol 23, No.10 (October, 2011) An observation about corporate security departments : Slightly Skeptical Euromaydan Chronicles, June 2014 : Greenspan legacy bulletin, 2008 : Vol 25, No.10 (October, 2013) Cryptolocker Trojan (Win32/Crilock.A) : Vol 25, No.08 (August, 2013) Cloud providers as intelligence collection hubs : Financial Humor Bulletin, 2010 : Inequality Bulletin, 2009 : Financial Humor Bulletin, 2008 : Copyleft Problems Bulletin, 2004 : Financial Humor Bulletin, 2011 : Energy Bulletin, 2010 : Malware Protection Bulletin, 2010 : Vol 26, No.1 (January, 2013) Object-Oriented Cult : Political Skeptic Bulletin, 2011 : Vol 23, No.11 (November, 2011) Softpanorama classification of sysadmin horror stories : Vol 25, No.05 (May, 2013) Corporate bullshit as a communication method  : Vol 25, No.06 (June, 2013) A Note on the Relationship of Brooks Law and Conway Law


Fifty glorious years (1950-2000): the triumph of the US computer engineering : Donald Knuth : TAoCP and its Influence of Computer Science : Richard Stallman : Linus Torvalds  : Larry Wall  : John K. Ousterhout : CTSS : Multix OS Unix History : Unix shell history : VI editor : History of pipes concept : Solaris : MS DOSProgramming Languages History : PL/1 : Simula 67 : C : History of GCC developmentScripting Languages : Perl history   : OS History : Mail : DNS : SSH : CPU Instruction Sets : SPARC systems 1987-2006 : Norton Commander : Norton Utilities : Norton Ghost : Frontpage history : Malware Defense History : GNU Screen : OSS early history

Classic books:

The Peter Principle : Parkinson Law : 1984 : The Mythical Man-MonthHow to Solve It by George Polya : The Art of Computer Programming : The Elements of Programming Style : The Unix Haterís Handbook : The Jargon file : The True Believer : Programming Pearls : The Good Soldier Svejk : The Power Elite

Most popular humor pages:

Manifest of the Softpanorama IT Slacker Society : Ten Commandments of the IT Slackers Society : Computer Humor Collection : BSD Logo Story : The Cuckoo's Egg : IT Slang : C++ Humor : ARE YOU A BBS ADDICT? : The Perl Purity Test : Object oriented programmers of all nations : Financial Humor : Financial Humor Bulletin, 2008 : Financial Humor Bulletin, 2010 : The Most Comprehensive Collection of Editor-related Humor : Programming Language Humor : Goldman Sachs related humor : Greenspan humor : C Humor : Scripting Humor : Real Programmers Humor : Web Humor : GPL-related Humor : OFM Humor : Politically Incorrect Humor : IDS Humor : "Linux Sucks" Humor : Russian Musical Humor : Best Russian Programmer Humor : Microsoft plans to buy Catholic Church : Richard Stallman Related Humor : Admin Humor : Perl-related Humor : Linus Torvalds Related humor : PseudoScience Related Humor : Networking Humor : Shell Humor : Financial Humor Bulletin, 2011 : Financial Humor Bulletin, 2012 : Financial Humor Bulletin, 2013 : Java Humor : Software Engineering Humor : Sun Solaris Related Humor : Education Humor : IBM Humor : Assembler-related Humor : VIM Humor : Computer Viruses Humor : Bright tomorrow is rescheduled to a day after tomorrow : Classic Computer Humor

The Last but not Least Technology 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

Copyright © 1996-2021 by Softpanorama Society. was initially created as a service to the (now defunct) UN Sustainable Development Networking Programme (SDNP) without any remuneration. This document is an industrial compilation designed and created exclusively for educational use and is distributed under the Softpanorama Content License. Original materials copyright belong to respective owners. Quotes are made for educational purposes only in compliance with the fair use doctrine.

FAIR USE NOTICE This 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


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.

Last modified: August 23, 2020