This is just going to be some boring examples of control structures. I don't have a lot to say about this stuff, but it would be a bad form not to at least mention them. So here we go.
# basic "If"
if boolean:
x = 1
else:
x = 0
# Not so basic "If"
# Notice the new keywords!
if (boolean and otherboolean) or ( not boolean ): #oops, this is just if(boolean), oh well... :~)
x = 1
elif not otherboolean:
x = 0
else:
x = 100000000000000000000 # Big numbers make if statements less boring!
Notice the new keywords if, elif, else, and, or, and not. That's pretty much all there is to it.
...zzzzzzzz...
Oh, yes, "While" loops!
Here's another example:
# This is it...
while i < 100:
i + 1
# More generally:
while condition == true:
"""do the following"""
...
...
condition = false.
# Infinite Loop:
while 1:
print "I'm loopy!"
For loops are actually very interesting because they don't behave just like C for loops, although they can. For loops in Python iterate over Lists instead of just incrementing integers. They are probably my favorite constructs in Python, because the syntax is very intuitive and just downright pleasant.
# Basic For Loop
for item in list:
dosomething(item)
# The traditional C for loop has a different form in Python:
for x in range(0, 100):
dosomething(x)
# More interesting example:
def buglove( UIUC ):
for bug in UIUC:
if type( bug ) == type( chinese_lady_beetle() ):
crush( bug )
else:
hug( bug )
Aren't they just lovely?
They work in pretty much the exact same way. Here's some quick examples:
# Continue
nlist = []
for i in xrange(0,100):
if i == 0:
continue
nlist.append( 7 / i )
# Break
# How many heads can we flip in a row?
heads = 0
while 1:
if x = 0:
break
else:
x = random.rand(0,1)
heads += 1
# Pass
# If you don't want to do anything in a case
x = 0
while 1:
if x <= 100:
pass
elif x = 101:
print "Just enough Dalmations!"
else:
print "Argh! Too many Dalmations!"
break
x += 1
Case structures?
# Case In Python
age = raw_input("Enter Your Age:")
if age < 5:
print "You're too young for computers, Go Outside!"
elif age = 6:
print "I like case structures!"
elif age = 70:
print "You youngin's are spoiled with your 'Case' structures! Back in my day we had to flip bits with our toes!"
else: # Default case
print "This is so lame, Mike!"
These are really quite a bit more complicated, try and except are going to be handled later under the topic of "Exceptions", so check it out there if you're interested.