Python Concepts/Flow control

From Wikiversity
Jump to navigation Jump to search

Boolean Expressions[edit | edit source]

Python has a Boolean type. The two values for this type are True and False. Note the capitalization: the first letter must be capitalized. Most text editors, including IDLE, will highlight True and False when properly capitalized.

The bool() Function[edit | edit source]

If you need to convert something into a Boolean value, use the bool() function. For example:

>>> bool(1)
True
>>> bool(0)
False
>>> bool(500)
True
>>> bool(-1)
True


In Python, the integer 0 evaluates to False. All other integers will evaluate to True.[1]

Strings behave similarly: an empty string evaluates to False, all other strings evaluate to True.

>>> bool("Hello World!")
True
>>> bool("")
False
>>> bool("True")
True
>>> bool("False")
True
>>> bool("0")
True


Note that what is in the string does not matter: It can be "0", "False" or "ReallyReallyFalse": Everything that is not simply an empty string will evaluate to True.

This means we can write such useful constructs as if ( string ) which will execute a block of code only if the string is non-empty.

Comparison Operators[edit | edit source]

Python has a number of built-in comparison operators. They are very versatile and can often be used across data types.

Equality[edit | edit source]

The Python operator for Equality is ==. Let's try it out:

>>> 1 == 1
True
>>> "1" == "1"
True
>>> 2 + 4 == 24
False
>>> "2" + "4" == "24"
True

Conjunction[edit | edit source]

The Python operator for conjunction is and.

>>> True and False
False
>>> True and True
True
>>> False and False
False
>>> False and True
False

The and operator works by evaluating until it runs into something False, and return the value that evaluated to False. If everything is True, it returns the last thing it evaluated.

>>> "a" and "b"
'b'
>>> "" and "b"
''
>>> True and 7
7
>>> True and [] and "a"
[]

This means that in a Boolean context the result is evaluated to True or False in the way we would expect, using the actual value means that we can benefit from useful side effects in other contexts.

Disjunction[edit | edit source]

The or operator works similar to the and operator. It returns the first value to be True, or the final value if there is no True value.

>>> False or ('a', 'b') or 'c'
('a', 'b')
>>> False or True
True
>>> '' or False
False
>>> '' or False or ()
()

Inversion[edit | edit source]

The not operator returns the opposite of the value passed to it.

>>> not True
False
>>> not False
True
>>> not 1
False
>>> not 0
True
>>> not ""
True
>>> not "a"
False
>>> not ("a", "")
False
>>> not ("", "a")
False
>>> not ("", "")
False


Interestingly, Python treats the set of strings as having a True value, even if the strings themselves are empty. Since the set the set contains two strings, it really isn't empty, even if the strings are.

Comparison[edit | edit source]

The is operator compares two values to see if they match. Note that floating point and integer values are not the same thing.

>>> 1 is 1
True
>>> 1 is 2
False
>>> "a" is "a"
True
>>> "a" is "abc"
False
>>> "a" is ("a", "b")
False
>>> 1.0 is 1
False
>>> 1.0 is 1.0
True


is chains like the and operator, evaluating to False if any part is False.

>>> 1 is 1 is 1
True
>>> 1 is 1 is 2
False

Contains[edit | edit source]

The in operator checks a list of things or a string to see if a value is present. Note that floating point and integers evaluate to the same thing for in. If an array is present then it checks against the whole value of the components of the array, not against the contents of the components in the array.

>>> 1 in (1, 2)
True
>>> 3 in (1, 2)
False
>>> "a" in "abc"
True
>>> "d" in "abc"
False
>>> "a" in ("123", "abc")
False
>>> "a" in ("abc", "123")
False
>>> "abc" in ("abc", "123")
True
>>> 1 in (1.2, 2.0)
False
>>> 1 in (1.0, 2.0)
True
>>> 1.0 in (1, 2)
True


in needs an array of values to check against, checking in the same way as is produces an error.

>>> 1 in 1
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: argument of type 'int' is not iterable

Flow Control[edit | edit source]

Now that you know all these great ways to work with Booleans, let's use them!

if, elif, and else[edit | edit source]

Python the keyword if to determine if it should execute a section of code. You can tell which lines are in this section by the level of indentation. The general format of if goes like this:

if [Boolean Expression]:
    some code
rest of code

This allows for very simple logic. What if you want to have two options, similar to case in other languages? Instead of Case, python uses elif.

if [Boolean Expression]:
    code
elif [Boolean Expression]:
    More code
else:
    Even more code
rest of program

If the Boolean expression for the first if is True, nothing in the elif section will execute, nor will anything in the else section. If there are multiple things that could evaluate to True, use multiple if statements.

That code sample also introduced the else statement. else gets executed if the if statement's Boolean expression, and the Boolean expressions for all the elif statements (if there are any), evaluate to False.

So, how about some actual code? Here's a simple program; try entering this into IDLE and running it. Don't forget to define the function.

name = raw_input("What is your name?")
if name == "":
    print "Hey! You didn't enter a name!"

elif name == "spam" or name == "eggs":
    print "A moose once bit my sister!"

else:
    print "Nice to meet you, %s." % name


While[edit | edit source]

While is our first example of a loop. While evaluates a Boolean expression, and if that expression is True, it runs some section of code. It then re-evaluates that Boolean expression: if it still evaluates to True, then it runs again. It keeps running - possibly forever! - until that loop evaluates to False, at which point the program continues with whatever comes after the while loop.

Let's take our previous example. That program ran once, and even if nothing was entered, it was done. Let's suppose we instead want a program that "won't take no for an answer": We'll use a while loop to make the prompt show up again and again until we get some response:

name = raw_input("What is your name?")
while name == "":
    print "Hey! You didn't enter a name!"
    name = raw_input("Okay, REALLY tell me your name this time:")
if name == "spam" or name == "eggs":
    print "A moose once bit my sister!"
else:
    print "Nice to meet you, %s" % name


That's even better. However, there are a couple of things I don't like about it. First, I don't like that first Boolean expression. After all, we know that:

bool("") == False


Therefore, wouldn't it make more sense just to test if name is False than to test if it's True that it's equal to ""?

while bool(name) == False:


And do we really want to test if it's True than to Test that it's True that it's equal to False?

while not bool(name):


That's right! Python has a "not" keyword, which acts a lot like ! in other languages.

We're missing one last thing: whatever comes after the "while" is automatically evaluated as a boolean expression. That means that in many cases (this one included) we can leave out the bool(). (There will still be cases where it's needed, though, so remember that it exists!)

while not name: # This is exactly the same as 'while name == "":', but a lot clearer. 

Okay, good? Cool. It's time to add a new feature: The for loop.

For concept in lesson: learn(concept)[edit | edit source]

If you thought the Python idioms for the while loop were cool, the for loop is even better. A for loop takes this basic form syntax-wise:

for [variable name] in [sequence]:
    code

The for loop will execute enough times that each element of "sequence" is assigned to "variable" once. For example:

for i in [1, 2, 3]:
    print i  # 1 2 3

Of course, any data type could be within the sequence. While we're at it, let's use a descriptive variable name:

for letter in ['a','b','c']:
    print letter # output is a b c

As you can see, then, for loops make it easy to iterate over a sequence, or in simpler terms, to do something with each entry in a list. For loops are also excellent for times when you need to run a while loop a fixed number of times. Let's compare doint that with a for loop and a while loop:

c = 0
while c < 10:
    some_function(c)
    # code, code code
    c += 1

While this is legal Python code, it's not really descriptive. Furthermore, when working with large code blocks, it's easy to forget to add 1 to the variable (in this case 'c') at the end. Fortunately, we can do the same thing with a for loop, in a clearer fashion.

for i in range(10):
     some_function(i)
     # More code as needed

Note how we don't have to worry about declaring i, or automatically incrementing it. It's also significantly faster, although most of the time your code will run fast enough anyway.

Note that while we used 'i' as the variable name, you could use anything else. As a general rule, when using the variable as a counter, simply use 'i'; this convention is widely followed and helps other programmers know exactly why you chose a for loop. Otherwise, use a descriptive variable name. For example:

list_of_dates = some_function()
for date in list_of_dates:
    do_something_with(date)

The main reason we use while loops is sometimes we need to repeatedly prompt a user to get a valid input. Simply put, use while when you don't know or can't calculate how many times a loop will run. If you can, use for.

  1. http://docs.python.org/3/library/stdtypes.html#truth