Top | Previous | Next |
Control Flow |
Control flow are the parts of a language that make it do things differently based upon various conditions. In other words: ifs and loops. Python has all of the basic control flow statements that you'd expect. if Statements If statement should be familiar to anyone with a passing knowledge of programming. The idea of an if is that you want your script to execute a block of statements only if a certain condition is true. For example, this script won't do anything. x = 15 if x < 10: print "this will never show"
You can use the if...else form of an if statement to do one thing if a condition is true, and something else if the condition is false. This script will print out "this will show!" x = 15 if x < 10: print "this will never show" else: print "this will show!"
Lastly, you can use the if...elif form. This form combines multiple condition checks. "elif" stands for "else if". This form can optionally have a catch-all "else" clause at the end. For example, this script will print out "three": x = 3 if x == 1: print "one" elif x == 2: print "two" elif x == 3: print "three" else: print "not 1-3"
while Loops A while loop will repeat a block of statements while a condition is true. This code will print out the contents of the items in the list. This code uses a function called len, which is a built-in function that returns the length of a list or string. listOfFruit = ['Apples', 'Oranges', 'Bananas'] x = 0 while x < len(listOfFruit): print listOfFruit[x] x = x + 1 for Loops Python's for loop may be a bit different than what you're used to if you've programmed any C. The for loop is specialized to iterate over the elements of any sequence, like a list. So, we could re-write the example above using a for loop eliminating the counter x: listOfFruit = ['Apples', 'Oranges', 'Bananas'] for item in listOfFruit: print item
Much more graceful! You'll often see the for loop used instead of the while loop, even when you simply want to iterate a given number of times. To do this with the for loop, you can use the built-in function range. The range function returns a variable-size list of integers starting at zero. Calling range(4) will return the list [0, 1, 2, 3]. So, to have a for loop repeat 4 times, you simply can do: for x in range(4): print "this will print 4 times"
break and continue in Loops You can stop a loop from repeating in its tracks by using the break statement. This code will print out "Loop" exactly two times, and then print "Finished". for x in range(10): if x >= 2: break print "Loop" print "Finished"
You can use the continue statement to make a loop stop executing its current iteration and skip to the next one. The following code will print out the numbers 0-9, skipping 4 for x in range(10): if x == 4: continue print x |