Notes: Conditionals

posted by: Ms. Martin 2 March 2010 12 Comments
A decision is when a program has more than one choice of actions depending on the situation.  We can use conditional statements in our Python programs to make the program react differently.  In Python, conditional statements are if, else and elif.

Syntax

The if statement simply says  “If this, do that.”  The if statement is a container — don’t forget that with Python you MUST indent after a colon!

name = raw_input("What’s your name? ")

if(name == "Nick"):
    print("Hello, master, would you like some ice cream?")

This code creates a variable named name. It then prompts the user for a name and stores whatever value the user types in in the name variable.  When it enters the if statement, it checks whether name is equal to the value “Nick.”  If they are equal, the message is printed.  Otherwise, nothing happens.  TRY THIS! Kind of boring if you put anything but “Nick” in, right?  You can use else to add another message:

name = raw_input("What’s your name? ")

if(name == "Nick"):
    print("Hello, master, would you like some ice cream?")
else:
    print("Go away!!!")

What if we want to react in a special way to two people’s names?  We can use elif:

name = raw_input("What’s your name? ")

if(name == "Nick"):
    print("Hello, master, would you like some ice cream?")
elif(name == "Sandra"):
    print("Hello, mistress, would you like some chocolate?")
else:
    print("Go away!!!")

Unsurprisingly, elif stands for else if.  In this case, if the name plugged in wasn’t Nick, then we try to see if it was Sandra.  If it still isn’t Sandra, then we print “Go away!!!” You can have as many elifs as you want.

Comparison operators

The following operators can be used to make comparisons.  Try using them with different kinds of values.
For example, what do you think the following would do using the name variable from the examples above?

name = "goooooo"

if("banana" < name):
    print("YES!")
operator function
< less than
<= less than or equal to
> greater than
>= greater than or equal to
== equal
!= not equal

Examples

from turtle import *

# Prompts the user for a shape to draw and draws it if possible.
def draw_shape():
    shape = raw_input("What shape do you want me to draw? ")
    if(shape == "circle"):
        radius = int(raw_input("How big of a circle? "))
        if(radius > 300): # Notice you can have an if statement inside of another if statement!
            print("That's too big!")
        else: # Only draw a circle if it's small enough.
            circle(radius)
    elif(shape == "hippo"):
        print("Sorry, I have no idea how to draw a hippo!!")
    elif(shape == "square"): # More than one elif
        side = int(raw_input("How big of a square? "))
        for i in range(4):
            forward(side)
            right(90)
    else:
        print("You asked for " + shape + " but I don't know that shape!")

draw_shape()
# Asks what type of conversion the user wants to complete and does it.
def convert():
    conv_type = int(raw_input("What kind of conversion do you want to do? 1) feet to miles 2) cm to in\n"))
    if(conv_type == 1):
        feet = float(raw_input("How many feet? "))
        miles = feet / 5280
        print("There are " + str(miles) + " miles in " + str(feet) + " feet.")
    elif(conv_type == 2):
        cm = float(raw_input("How many centimeters? "))
        inches = cm / 2.54
        print("There are " + str(inches) + " inches in " + str(cm) + " centimeters.")
    else:
        print("Should have chosen 1 or 2!!")

convert()
# In this example, all ages are checked and multiple messages may be printed
def age_check(age):
    print("Age: " + str(age))
    if(age < 15):
        print("\tCan't open a MySpace account.") # notice that '\t' adds a tab character
    if(age < 16):
        print("\tCan't get a permit.")
    if(age < 18):
        print("\tCan't vote.")
    if(age < 21):
        print("\tCan't drink.")
    else:
        print("\tYou're old!!") # This else only runs if age is >= 21

# Elifs are mutually exclusive, so only one message is printed
def age_check2(age):
    print("Age: " + str(age))
    if(age < 15):
        print("\tCan't open a MySpace account.")
    elif(age < 16):
        print("\tCan't get a permit.")
    elif(age < 18):
        print("\tCan't vote.")
    elif(age < 21):
        print("\tCan't drink.")
    else:
        print("\tYou're old!!")

# I thoroughly test my functions to make sure they work as expected
age_check(15)
age_check(10)
age_check(17)
age_check(40)
age_check(19)
print("\n=======age_check2=========\n") # notice that '\n' adds a newline character
age_check2(15)
age_check2(10)
age_check2(17)
age_check2(40)
age_check2(19)
1 Star2 Stars3 Stars4 Stars5 Stars (5 votes, average: 2.60 out of 5)
Loading ... Loading ...

Leave a comment

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>