I've been rather busy lately, so I haven't managed to write another Python article, but I finally squeezed out some time for part 3. If you haven't read them yet, I highly recommend reading parts one and two first.

Operators and Expressions

Most of the lines of code you write will be expressions. An expression in a programming sense is similar to an expression in a mathematical sense. It is basically a line of code that performs an action and has an outcome.

Some examples of expressions are as follows:

2 + 3a * b(c / d) - e

Expressions are made up of two parts, operands and operators. Operands are the items in the expression, for example, the 2, 3, a, b, c, d and e in the above examples. Operators are the actions in the expression, for example, the +, *, / and - in the examples above.

Python has a number of operators, including bitwise operators which are used for dealing with the bits in bytes and integers.

Flow Control

As your code executes, there are ways to control which statements and expressions are executed, and when. The statements used to do this are called flow control statements.

if Statements

if statements control whether or not to execute blocks of code. An if statement has three parts, though only the first part is mandatory.

The first part of the if statement is the actual if part. The if block contains the word, "if," an expression to be evaluated, a colon, and an indented block of code. For example:

a = 2if a == 2:    print 'a is 2!'

The above example evaluates the identifier a to see if its value is 2, and prints "a is 2!" if it is.

The second part of the if statement is the else block. The else block is executed when the expression in the if block evaluates to False. For example:

a = 3if a == 2:    print 'a is 2!'else:    print 'a is not 2.'

The above example evaluates the identifier a to see if its value is 2, and since it is not 2 (it is 3) it prints "a is not 2."

The third part of the if statement is the elif block. An elif is the combination of the else and the if. It is used between the initial if and the else right at the end.

While both the if and else blocks can appear only once, the elif block can appear as many times as is necessary. For example:

a = 6if a == 1:    print 'a is 1'elif a == 2 or a == 4:    print 'a is 2 or 4'elif a == 3 or a == 5:    print 'a is 3 or 5'elif a == 6'    print 'a is 6'else:    print 'a is not in the range 1 to 6'

Loops

While programming we often have to perform the same task over and over again with a small variation each time. We can abstract the code that performs the task a little, and introduce some variables that can be applied to this code to make it work for each particular set of values. This generic or abstract code can then be put into a loop so that the computer can run through the task over and over until the sets of values have all been evaluated.

There are different types of loops which all serve a particualr purpose, and work slightly differently.

while Loops

The while statement will repeatedly execute a block of statements as long as a condition is true. It is a very simple mechanism, but a very powerful one. while loops are very useful when you need to repeat a set of statements, but don't know exactly how many times you need to do so. For example:

counter = 0input = int(raw_input('Type in a number to count up to: '))while counter < input:    counter += 1    print 'Counting:', counterprint 'Done!'

This example asks the user for a number, and then counts up until the user's number is reached by comparing the counting number with the user's number.

for Loops

Another type of loop is the for ... in ... statement. A for loop is used to iterate over a sequence of items, when you know how many items are in that sequence. In other words, the for loop allows you to go over each item in a list and do something with it. For example:

for counter in [1, 2, 3, 4, 5, 6]:    print 'Counting:', counter

This short example will count from 1 to 6. The list contains the numbers 1 to 6, and the for loop will go through the list and set counter to each value as it iterates over the list.

The break Statement

The break statement is used with loops to control when the looping is terminated. When a break statement is executed, it forces the loop to stop running immediately, and to move onto the next bit of code. break statements are useful for stopping a loop should you reach the result you want early. For example:

while True:    input = raw_input('Type in something (or "quit" to exit): ')    if input == 'quit':        break    print 'You typed:', inputprint 'Bye!'

In the above example, we use a while loop to repeat our code indefinitely (True always evaluates to true) and if the user types in "quit" then we break out of the loop.

The continue Statement

The continue statement is somewhat similar to the break statement, except that it does not exit the loop, it simply skips everything else inside the loop for this iteration, and moves onto the next cycle.

for counter in [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]:    if counter % 4 == 0:        print 'Counter is a multiple of 4.'        continue    print counter, '-', (counter // 2), '=', (counter - (counter // 2))print 'Finished!'

In the above loop, while counting from 1 to 10, if we encounter a number that is divisible by 4 (% = modulus) then we print out a specific message. For all other values we simply subtract half of the number from the original number.

Conclusion

In this lesson we learned about operators, expressions, and flow control. We've dealt very briefly with flow control, but as you start learning more and more Python, and as you start becoming more and more proficient in Python, you'll learn more of how to use the statements above to control how your programs work.

Update: Part 4


Comments

comments powered by Disqus