Python Programming/Conditional Statements

From Wikibooks, the open-content textbooks collection

Jump to: navigation, search
Previous: Decision Control Index Next: Loops

Contents

[edit] Decisions

A Decision is when a program has more than one choice of actions depending on a variable's value. Think of a traffic light. When it is green, we continue our drive. When we see the light turn yellow, we proceed to reduce our speed, and when it is red, we stop. These are logical decisions that depend on the value of the traffic light. Luckily, Python has a decision statement to help us when our application needs to make such decision for the user.

[edit] If statement

Here is a warm-up exercise - a short program to compute the absolute value of a number:

n = raw_input("Integer? ")#Pick an integer.  And remember, if raw_input is not supported by your OS, use input()
n = int(n)#Defines n as the integer you chose. (Alternatively, you can define n yourself)
if n < 0:
    print ("The absolute value of",n,"is",-n)
else:
    print ("The absolute value of",n,"is",n)

Here is the output from the two times that I ran this program:

Integer? -34
The absolute value of -34 is 34

Integer? 1
The absolute value of 1 is 1

What does the computer do when it sees this piece of code? First it prompts the user for a number with the statement "n = raw_input("Integer? ")". Next it reads the line "if n < 0:". If n is less than zero Python runs the line "print "The absolute value of",n,"is",-n". Otherwise python runs the line "print "The absolute value of",n,"is",n".

More formally, Python looks at whether the expression n < 0 is true or false. An if statement is followed by an indented block of statements that are run when the expression is true. After the if statement is an optional else statement and another indented block of statements. This 2nd block of statements is run if the expression is false.

There are several different tests that an expression can have. Here is a table of all of them:

operator function
< less than
<= less than or equal to
> greater than
>= greater than or equal to
== equal
!= not equal


Another feature of the if command is the elif statement. It stands for "else if," which means that if the original if statement is false and then the elif statement is true, execute the block of code following the elif statement. Here's an example:

a = 0
while a < 10:
    a = a + 1
    if a > 5:
        print (a,">",5)
    elif a <= 7:
        print (a,"<=",7)
    else:
        print ("Neither test was true")

and the output:

1 <= 7
2 <= 7
3 <= 7
4 <= 7
5 <= 7
6 > 5
7 > 5
8 > 5
9 > 5
10 > 5

Notice how the elif a <= 7 is only tested when the if statement fails to be true. elif allows multiple tests to be done in a single if statement.

[edit] If Examples

High_low.py

#Plays the guessing game higher or lower 
# (originally written by Josh Cogliati, improved by Quique)
 
#This should actually be something that is semi random like the
# last digits of the time or something else, but that will have to
# wait till a later chapter.  (Extra Credit, modify it to be random
# after the Modules chapter)
number = 78
guess = 0
 
while guess != number : 
    guess = raw_input("Guess an integer: ")
    guess = int(guess)
    if guess > number :
        print ("Too high")
 
    elif guess < number :
        print ("Too low")
    else:
        print ("Just right" )

Sample run:

Guess an integer:100
Too high
Guess an integer:50
Too low
Guess an integer:75
Too low
Guess an integer:87
Too high
Guess an integer:81
Too high
Guess an integer:78
Just right

even.py

#Asks for a number.
#Prints if it is even or odd
 
number = raw_input("Tell me a number: ")
number = float(number)
if number % 2 == 0:
    print (number,"is even.")
elif number % 2 == 1:
    print (number,"is odd.")
else:
    print (number,"is very strange.")

Sample runs.

Tell me a number: 3
3 is odd.

Tell me a number: 2
2 is even.

Tell me a number: 3.14159
3.14159 is very strange.

average1.py

#keeps asking for numbers until 0 is entered.
#Prints the average value.
 
count = 0
sum = 0.0
number = 1.0  # set this to something that will not exit
#               the while loop immediately.
 
print ("Enter 0 to exit the loop")
 
while number != 0:
    number = raw_input("Enter a number: ")
    number = float(number)
    if number != 0:
       count = count + 1
       sum = sum + number
 
print "The average was:",sum/count

Sample runs

Enter 0 to exit the loop
Enter a number:3
Enter a number:5
Enter a number:0
The average was: 4.0

Enter 0 to exit the loop
Enter a number:1
Enter a number:4
Enter a number:3
Enter a number:0
The average was: 2.66666666667

average2.py

#keeps asking for numbers until count have been entered.
#Prints the average value.
 
sum = 0.0
 
print ("This program will take several numbers, then average them.")
count = raw_input("How many numbers would you like to sum:")
count = int(count)
current_count = 0
 
while current_count < count:
    current_count = current_count + 1
    print ("Number",current_count)
    number = input("Enter a number: ")
    sum = sum + number
 
print "The average was:",sum/count

Sample runs

This program will take several numbers, then average them.
How many numbers would you like to sum:2
Number 1
Enter a number:3
Number 2
Enter a number:5
The average was: 4.0

This program will take several numbers, then average them.
How many numbers would you like to sum:3
Number 1
Enter a number:1
Number 2
Enter a number:4
Number 3
Enter a number:3
The average was: 2.66666666667


[edit] If Exercises

  1. Write a password guessing program to keep track of how many times the user has entered the password wrong. If it is more than 3 times, print You have been denied access. and terminate the program. If the password is correct, print You have successfully logged in. and terminate the program.
  2. Write a program that asks for two numbers. If the sum of the numbers is greater than 100, print That is a big number and terminate the program.
  3. Write a program that asks the user their name. If they enter your name, say "That is a nice name." If they enter "John Cleese" or "Michael Palin", tell them how you feel about them ;), otherwise tell them "You have a nice name."

[edit] Switch

A switch is a control statement present in most computer programming languages to minimize a bunch of If - elif statements. Sadly Python doesn't officially support this statement, but with the clever use of an array or dictionary, we can recreate this Switch statement that depends on a value.

x = 1
 
def hello():
  print ("Hello")
 
def bye():
  print ("Bye")
 
def hola():
  print ("Hola is Spanish for Hello")
 
def adios():
  print ("Adios is Spanish for Bye")
 
# Notice that our switch statement is a regular variable, only that we added the function's name inside
# and there are no quotes
menu = [hello,bye,hola,adios]
 
# To call our switch statement, we simply make reference to the array with a pair of parentheses
# at the end to call the function
menu[3]()   # calls the adios function since is number 3 in our array.
 
menu[0]()   # Calls the hello function being our first element in our array.
 
menu[x]()   # Calls the bye function as is the second element on the array x = 1

This works because Python stores a reference of the function in the array at its particular index, and by adding a pair of parentheses we are actually calling the function. Here the last line is equivalent to:

if x==0:
    hello()
elif x==1:
    bye()
elif x==2:
    hola()
else:
    adios()


[edit] Another way

Source

Another way is to use lambdas. Code pasted here without permissions.

result = {
  'a': lambda x: x * 5,
  'b': lambda x: x + 7,
  'c': lambda x: x - 2
}[value](x)
Previous: Decision Control Index Next: Loops