View Category

Perform an action if a condition is true (IF .. THEN)

Given a variable name, if the value is "Bob", display the string "Hello, Bob!". Perform no action if the name is not equal.
python
if name == 'Bob':
print 'Hello, Bob!'

Perform different actions depending on a boolean condition (IF .. THEN .. ELSE)

Given a variable age, if the value is greater than 42 display "You are old", otherwise display "You are young"
python
if age > 42:
print 'You are old'
else:
print 'You are young'
print age > 42 and 'You are old' or 'You are young'

Perform different actions depending on several boolean conditions (IF .. THEN .. ELSIF .. ELSE)

python
if age > 84:
print 'You are really ancient'
elif age > 30:
print 'You are middle-aged'
else:
print 'You are young'

Replacing a conditional with many branches with a switch/case statement

Many languages support more compact forms of branching than just if ... then ... else such as switch or case or match. Use such a form to add an appropriate placing suffix to the numbers 1..40, e.g. 1st, 2nd, 3rd, 4th, ..., 11th, 12th, ... 39th, 40th
python
def affix(num):
num = num == 1 and str(num) + 'st' or num == 2 and str(num) + 'nd' or \
num == 3 and str(num) +'rd' or str(num) + 'th'
return num

print [affix(x) for x in xrange(1,41)]

Perform an action multiple times based on a boolean condition, checked before the first action (WHILE .. DO)

Starting with a variable x=1, Print the sequence "1,2,4,8,16,32,64,128," by doubling x and checking that x is less than 150.
python
x = 1
while x < 150:
print '%s, ' % x,
x *= 2

Perform an action multiple times based on a boolean condition, checked after the first action (DO .. WHILE)

Simulate rolling a die until you get a six. Produce random numbers, printing them until a six is rolled. An example output might be "4,2,1,2,6"
python
import random, itertools

def dice():
while True:
yield random.randint(1,6)

print ", ".join(str(d) for d in itertools.takewhile(lambda x: x < 6, dice()))

Perform an action a fixed number of times (FOR)

Display the string "Hello" five times like "HelloHelloHelloHelloHello"
python
print "Hello" * 5
for i in range(5):
print "Hello"

Perform an action a fixed number of times with a counter

Display the string "10 .. 9 .. 8 .. 7 .. 6 .. 5 .. 4 .. 3 .. 2 .. 1 .. Liftoff!"
python
print " .. ".join(str(i) for i in range(10, 0, -1)), ".. liftoff!"