Friday, February 14, 2014

Hustle and Flow… control

Common operators

Now that we’ve covered a bit of the basics, I wanted to give a list of some of the basic operators and what they do, both for review and for future reference. Some of these you have seen already. Many of them will be new.

Arithmetic Operators

Meaning / Effect

+

addition

-

subtraction

*

multiplication

/

division

%

modulo:
This performs an integer division and returns the remainder instead of the quotient. So 10 % 3 returns 1 because 3 goes into 10 three times with a remainder of 1.

**

exponent:
2 ** 3 = 8

//

Floor division:
Returns a float value rounded down to the nearest integer.
9.0 // 2.0 = 4.0

+=

Adds a value to a variable.
x += 1 is equal to x = x + 1

-=

Subtracts a value from a variable.
x -= 1 is equal to x = x 1 1

*=

Multiplies a variable by a value.
x *= 2 is equal to x = x * 2

/=

Divides a variable by a value.
x /= 2 is equal to x = x / 2

There is another type of object called a boolean. A boolean is simply a object that contains a value of True or False. Booleans are very important for writing intelligent programs. Example: x = True. All of the below comparison operators return boolean objects, meaning True or False.

Comparison Operators

Meaning / Effect

==

Compares two objects,
If they are equal it returns True otherwise it returns False

!=

Compares two objects,
If they are not equal returns True otherwise it returns False

>=

Compares two objects,
If left side object is greater than or equal to the right side object returns True, otherwise returns False

<=

Compares two objects,
If left side object is less than or equal to the right side object returns True, otherwise returns False

>

Compares two objects,
If left side object is greater than the right side object returns True, otherwise returns False

<

Compares two objects,
If left side object is less than the right side object returns True, otherwise returns False

 

Sequence / Collection Operators

Meaning / Effect

in

Tests if an object is in a sequence object. Returns True if the object is in the list, otherwise returns False.
Example:
’x’ in [‘x’, ‘y’, ‘z’] returns True
’x’ in [1, 2, 3] returns False
’x’ in ‘ham’ returns False

 

Logical Operators

Meaning / Effect

and

Usage: x and y
If x = True and y = True returns True
If x or y = False returns False
If x and y = False returns False

or

Usage: x or y
If x = True and y = True returns True
If x or y = True returns True
If x and y = False returns False

not

Reverses the outcome of True/False evaluation
’x’ in ‘ham’ returns False
’x’ not in ‘ham’ returns True

If / else statements

Now that we have all of these lovely comparison operators let’s start putting them to good use. The if / else statement allows us to make decisions within our programs intelligently. Let’s dive in, beginning with the ‘if’ statement. It works like this:

if <condition is True>:
    <do something>

Notice that the ‘do something’ portion of the statement is indented just like in the loop statements we covered in the previous post. So, let’s do something with it, start by making an integer variable and set it equal to 5:

x = 5
if x > 0:
    print “x is a positive number.”

image

Big deal right? We already knew that five is a positive number. But what if we had a range of numbers and we wanted to know which ones are positive and which are negative? Perhaps we can combine the if statement with the for loop we covered in the last post…

numbers = (5, 15, –2, –9, 5, 13, –2, 7)
for number in numbers:
    if number > 0:
        print number,

image

You can see that combining the simple tools we have learned so far will allow us to write very complex and powerful programs. Let’s take the same tuple of numbers from the last example and write a program that tells us if a number is odd or even. In this instance we are going to need to do something if the number is even and something else if the number is not even. And, as you might have been able to tell the the name, we are going to use the “else” statement. The else statement is a pretty simple concept, it defines what needs to be done if the ‘if’ condition isn’t true. In the last example when ‘if’ was true, we did something. If it wasn’t true, we did nothing. Now with the else statement we can cover all our bases.

for number in numbers:
    if number % 2 == 0:
        print number, “is even.”
    else:
        print number, “is odd.”

image

Now this is starting to look like programming. Let’s walk through it line by line.

Line 1: “For each number in the tuple called numbers:

Line 2: The second line uses the modulo mentioned earlier in this post. It provides us with the remainder left over after a number has been divided. In this case we are saying: “If the number from the list has a remainder of zero when we divide it by 2 then…”

Line 3: “print the number, followed by “is even”. Because a number that can be evenly divided by 2 is always even.

Line 4: “Otherwise, if the number cannot be evenly divided by two…”

Line 5: “print the number, followed by “is odd.” Because any number that is not even is odd.

Pretty simple huh? But it is significant. This is the first logically driven program we have written so far. Not terribly exciting, but consider the fact that you can input any number in the universe into this program and it will tell you whether it is odd or even, and it only took 5 lines of code. You can logically cover all numbers from -infinity to infinity with just these simple lines. Imagine what you can do with a few more.

There’s one more statement that can be used in the if/else statement. It’s called ‘elif’ (short for else if). It is pretty simple also. An ‘elif’ simply adds another testing condition into the statement. An ‘elif’ gets tested for after the if condition is found to be false. So, if we wanted to not only find if a number is odd or even, but also wanted to know if it was divisible by 5. We could modify our tests like so using some ‘elif’ statements.

for number in numbers:
    if number % 2 == 0 and number % 5 == 0:
        print number, “is even and a multiple of 5.”
    elif number % 2 == 0:
        print number, “is even”
    elif number %5 == 0:
        print number, “is odd and a multiple of 5.”
    else:
        print number, “is odd.”

image

Now, there are many different ways to write the same code and this isn’t the most efficient, BUT I don’t want to confuse you too much at this point so I am trying to keep it simple. I’ll walk you through the logic of the if/else statements I used so you can see why I’m doing things in this order. The first thing I test for is if the number is even AND  (notice the logical operator I used, see above tables for details) is a multiple of 5. If that test comes back true then I print the response. If it’s not true, then I test if it is even, without worrying about the multiple of 5. If both of those aren’t true then I know that the number is odd. So all I need to test for now is if it can be divided by 5. If it can then it is an odd multiple of 5, if it can’t then it is just an odd number.

We’ve got a lot of the pieces we need for starting to really start writing some programs. There is still plenty more to learn but with the knowledge you’ve got so far you are well on your way to writing some simple programs. Next time we’ll cover writing functions. Only a few more lessons and you’ll be looking for your first entry level python programming job. Huzzah!!! XD


BONUS
If you are interested in a more efficient solution to the above problem, here you go.

for number in numbers:
    if number % 2 == 0:
        if number % 5 == 0:
            print number, “is even and a multiple of 5.”
        else:
            print number, “is even.”
    elif number % 5 == 0:
        print number, “is odd and a multiple of 5.”
    else:
        print number, “is odd.”

image

As you can see it is possible to have if statements inside of if statements. This is called “nesting” but we’ll talk about that in a later lesson. The reason this implementation is more efficient is because it requires the computer to do fewer tests on the number. In order to solve the problem that we set out to solve we need to know two pieces of information, is it even and is it a multiple of 5.

In the first set of code we tested number divided by 2 and then 5. Then we tested dividing by 2 again. Then we tested 5 again. If we follow the code we see that the minimum number of tests a number will go through is 2 (which is the minimum required we need to solve the problem),  but the maximum number of tests is 4 (in the case of an odd number). In this new implementation the maximum number of tests that can happen to a number is 2, the same as the minimum, which means this code is now “optimized”. There are still more ways to optimize it and make it faster but it gets into advanced computer sciencey subjects I’d prefer to avoid for the time being. All things in time…

No comments:

Post a Comment