Jump to content

Truth and flow control in Python: Difference between revisions

From IdeaWazaWiki
fix a couple typos
woot.
Line 41: Line 41:


==Flow Control==
==Flow Control==
Now that you know all these great ways to work with booleans, let's use them! Python uses a simple keyword called "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:
Now that you know all these great ways to work with booleans, let's use them!
 
===If, Elif, and Else==
Python uses a simple keyword called "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]:
  if [Boolean Expression]:
     some code
     some code
Line 67: Line 70:
  else:
  else:
     print "Nice to meet you, %s." % name
     print "Nice to meet you, %s." % name
===While===
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. Python as ! too, but not is often clearer when working with long boolean expressions.
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)===
The for loop is... (to be continued)

Revision as of 16:59, 24 February 2007

Boolean Expressions

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

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. As a general rule, try to avoid using Floating Point numbers in boolean expressions: use the int() operator to turn them into integers first.

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.

Comparison Operators

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

Equality

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

Flow Control

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

=If, Elif, and Else

Python uses a simple keyword called "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

One thing that's important to realize is that 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 elifs (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.

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

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. Python as ! too, but not is often clearer when working with long boolean expressions.

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)

The for loop is... (to be continued)