Notes: Conditionals

posted by: Ms. Martin2 March 201012 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!

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:

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