Monday, January 30, 2012

Lesson 2 - Integers and Functions

Integers

Last time, we learned all about strings and variables.  If you didn't see it, you find it here.

Today, I'm going to talk about integers—a term you may remember from mathematics.  An integer is a number with no fractional part.  3, 12, and 239487 are integers. 3.5, 7.32, and 0.45 are not integers; they are floating point numbers, but more on that later.

Open the Python command line interpreter.  If you don't remember how to do that, check out the first entry of this blog (found here).


Now that it's running, assign an integer to a variable like so:

myInteger = 10

Notice the lack of quotation marks.  That's because this variable is going to hold a number and not a string.  You could get the string "10" by doing this:

myString = "10"

Now if you print each variable

print myInteger
print myString


you aren't going to notice much difference (at least not right away).  (Note: The two lines above should be entered separately.  Don't try to enter them on the same line or there will be problems.  Whenever I put multiple lines together, just enter each one separately and hit return or Enter after each one.)





So what's the difference you ask?  Try this:


print myInteger + myInteger
print myString + myString



Whoa?  What happened?  10 + 10 ≠ 1010!  What happened?

Remember in Lesson 1 when we learned about string concatenation (from Latin meaning "linked together")?  That's what happens when you use the plus (+) sign with strings.  Instead of adding the values, it just puts one right after the other.

I'm sure someone out there is wanting to try this, so let's try it together:

print myInteger + myString




Oops an error!  Why can't we add or concatenate them?  It's because they are two different types.  A type is a kind of data.  A string is a type; an integer is another.  Unlike some other scripting languages, Python cares about what type your variable is, but unlike some other languages, you don't have to come out and say what type it is before you assign (with the equals(=) sign) it.  Once we said that myInteger equalled an integer, it's an integer.  If we reassign it like so:

myInteger = "Getting Started with Python"

suddenly it's a string.

It is possible to convert between types, and that leads me to our next topic


Functions


A function is a piece of code that exists somewhere else.  You pass variables to it, and it returns a value back.  For now, we are only going to deal with functions built-in to Python, but eventually, we are going to write our own functions.

The functions we are going to talk about first are these two:  int() and str()

A function call has two parts: the name of the function (eg int) and the parameters (whatever goes between the parentheses).  Some functions take no parameters, and some take a specific number of them in a certain order.

The int function takes one parameter and returns an integer representation of that parameter.  Let's try it.  First, let's make a string version of some number.

string = "42"

Now let's say we wanted to print the variable string with the number 1 added to it.  If we try

print string + 1

we get an error.


Why?  Because string is a string, and integers cannot be added to it.  What can we do?  Functions to the rescue!

We are going to call the int() function.  To do that, we put our variable between the parentheses.

print int(string) + 1


Tada!  It worked!  The function int() converted our string to an integer and then added one to the result.

For sake of learning, type this:

print string



Surprised?  Why does string still equal "42"?  That's because we never actually changed string, we just accessed its value.  In order to change string, we have to do something (like assign it) like this:

string = int(string) + 1
print string



Whoa!  What did we just do?  Remember the equals(=) sign isn't the same here as it is in mathematics.  In algebra, x = x + 1 has no value for x that will balance the equation.  In programming it's perfectly legal.

Here's what happened:
  1. Python converted string to an integer with the int() function.  It doesn't assign it just yet, but it remembers the integer 42 that int() returned.
  2. Python added 1 to 42 giving us 43.
  3. Python assigned the integer 43 to the variable string.
So is string still a string?  No, it's now an integer.  (How ironic!)  How can we be sure?  There's another function called type() that will tell us what type the value stored in a variable is.  Type this:

print type(string)



Aha!  <type 'int'> tells us that it's an integer.  What if we want a string?  Another function to the rescue!

string = str(string)
print type(string)



Voila!  The variable string is a string again!

Now let's try what we just did all at once.  (Yes, we can do that)  Don't panic, just follow me.

First, let's set string back to "42"

string = "42"


Now let's write our code to do what we want to do to that value:


string = str(int(string) + 1)


Now let's see what happened:


print string
print type(string)



It worked!  Don't worry if it looks complicated.  We just did the same thing we did above only this time we did it all at once.  Here's the breakdown of what happend in the line string = str(int(string) + 1):
  1. Python converted string to an integer with the int() function.  Again, it doesn't assign that value to string; string is still "42" at this point (and will remain so until #4)
  2. Python added one to the integer 42 that it remembered and got the integer 43
  3. Python converted the integer 43 that it was remembering to a string using the str() function.
  4. Python assigned the string "43" to the variable string.
Yes, that one line of code did all that.  Makes sense doesn't it?

But how did Python know what to do first?  Just like in mathematics, programming languages use parentheses to indicate what should happen first.  (It's actually a little more complicated than that, but don't worry about that now.)  It starts in the innermost parentheses and moves outward.


Documentation

How do we know what parameters functions like int() take?  We look at the Python documentation found here.  This is where you can find out many things about the Python language, including built-in types and functions.  To save you the trouble of finding it, the int() function is documented here.

Don't worry too much about what it says.  All it means is that we can convert other types to integers provided that the type is able to be converted.  To give an example of a bad conversion, type this:

print int("A")



Another error!  This was an error thrown by the int function to say that we did something wrong.  This is a good thing because otherwise it would have to pass back the integer 0, and that could have repercussions throughout the rest of our code.

A Word of Caution

At this point, I want to warn you to be careful when choosing your variable names.  You don't want to use variable names that are reserved (used by Python).  The cool thing about Python is that you can still do it, but it will mess up your program.  (If you do happen to overwrite something, don't panic.  The next time you start Python, everything will be back to normal.)

For instance DO NOT type something like this:

int = 10

This will get you into trouble because int no longer stands for a function; it stands for the number 10.

print int
print type(int)

Uh-oh!  We can't use int as a function anymore.  (I'm not sure quite how to get it back without quitting Python and starting it again.  Even so, doing that is beyond the scope of this blog.)


Math Operations

One last thing while we're still talking about integers.  Here's how you do simple arithmetic in Python:

print 3 + 3
print 3 - 3
print 3 * 3
print 3 / 3



The first two lines are obvious, but the next two may not be.

Addition: +
Subtraction: -
Multiplication: *
Division: /

There you have it, and you can use these symbols on integer variables too.

myInt = 7
print myInt * 6
myOtherInt = 3
print myInt * myOtherInt



And that's all for now.  Sorry it was so long, but I got a lot into this lesson.  If you're having difficulty understanding it all, try working through this post again piece by piece.

That's all for now!  See you back here for Lesson 3!

Review

  • Integers and strings are separate types in Python.
  • You can perform math operations on integers just like a calculator.
  • Functions are pieces of code stored elsewhere in your program.
  • Functions are called by placing parameters inside parentheses after the function name.
  • The int() and str() functions can convert other types to integers and strings respectively.
  • You can perform several functions on one line of code using parentheses.
  • The Python documentation contains useful information on functions and types in Python.
  • The standard math symbols in Python are + (addition), - (subtraction), * (multiplication) and / (division).






No comments:

Post a Comment