Boo's if statement is similar to Python's, accompanied by an elif statement and and else statement. No parentheses are needed around the condition being tested, and the body of each branch, which is intended, is introduced by a colon: n = 3 if n % 2: print "Odd." else: print "Even."
rating = 7 if rating >= 7: print "Good." elif rating >= 4: print "Average." else: print "Bad." Odd. Good. Boo also features an unless statement, which executes the associated code unless the condition is met: password = "ginger" unless password == "licorice": print "You can't come in." You can't come in. Boo provides a while loop with no surprises: n = 5 nFactorial = 1 while n > 1: nFactorial = nFactorial * n n = n - 1 print nFactorial 120 However, Boo's for loop is equivalent to a foreach loop in languages such as C#. It iterates through an enumerator: for n in [4,8,15,16,23,42]: print n 4 8 15 16 23 42 In order to obtain the functionality of a traditional for loop, one has to iterate over the sequence of numbers that would be passed through the for loop. This sequence of numbers can be generated by range: for n in range(5): print n 0 1 2 3 4 The range method can also take arguments specifying where the sequence should end and by what the starting point should be incremented to obtain the next number: for n in range(1,3): print n for n in range(1,3,2): print n 1 2
1
blog comments powered by Disqus |
|
|
|
|
|
|
|