Showing posts with label numbers. Show all posts
Showing posts with label numbers. Show all posts

Friday, January 30, 2015

Quick recipes for the master caster

Now that you know a few things about objects. I thought I throw out a few suggestions on how to use that knowledge in a practical way. So this is just a quick post to show you how to do some clever things with the knowledge you already have. I also want to introduce the idea of “type casting”. Type casting in Python means exactly the opposite of what it means in acting. When you “cast” an object, you change its type from one thing to another. Meaning you can change a float object to an int object, or an int object to a string object, a string to a list, and so on. Not all object types are interchangeable, although you can usually find a circuitous path to get an object of one type to another if you try hard enough.
Python has built in functions for converting between object types making casting really easy to do. The functions work as follows:
<proposed object type>(<object>)
Check out the image below for some examples of casting objects from one type to another.


As you can see, I began with an integer type object. I then converted it to a new float object. I then created a new string object from the float, followed by a list from the string. Float objects and Int objects can’t be converted to a list, but strings can because they are the same style object (collection/sequence). So in order to convert my Int to a list I first have to convert it to a string then convert the string to the list. Note, in the above example I assigned the converted objects to new variables. I did this because type casting is non-destructive, meaning that even when I assign b equal to float(a), the new object b is a float but object a is still an int.

So here is a list of the conversion functions for the objects you know so far and the types of objects that each conversion will accept.

Casting Function Accepted Object Types
int() – Integer cast Float objects,
String objects (must only have numeric characters, meaning no decimals, letters or special characters)

It is possible to convert letter characters to int objects using the int() cast function, but it involves using non-base ten numbering systems which I won’t go into here.
float() – Float cast Int objects,
String objects (must only have numeric characters and one or less decimal points, no letters or special characters)

Float cast accepts numbers and strings. The string can have a decimal but doesn’t have to, so ‘500’ and ‘500.0’ are ok. ‘50.0.0’ will not work.
str() – String cast Any object.

Any object can be converted to a string, though the results might not always be easily intelligible.
list() – List cast Any ‘iterable’ object.

List() cast accepts any ‘collection’ style object, including strings and tuples.
tuple() – Tuple cast Any ‘iterable’ object.

Tuple() cast accepts any ‘collection’ style object, including strings and lists.

So what can we do with this information? I’ll demonstrate a few bits of code that use some of the list functions I discussed in my last post and some type casting to do common programming tasks.

Finding an average value
If you have a list of numbers, but the length of the list might be different from time to time, you can find the average of the numbers in the list with a single line of code. For example, if I have a list myList = [5,7,2,100,3,1,1,23] I can find the average with the following line:
sum(myList) / float(len(myList))
Notice what happens when I don’t use the float() cast function. Remember, when a calculation is performed on two integers, an integer is returned. Averages are rarely integer values so in this case, we cast one of the values in the equation to a float type object in order to force the resulting value to have floating point precision. We could have also done the following:
float(sum(myList)) / len(myList)
Regardless of the side that we cast to float the outcome will be the same. If we don’t cast either side to a float object then we are performing an int divided by int calculation, which will produce an int result.

Rounding a float to the nearest integer
When you cast a float object to an int the decimal value of the float is just dropped. So 9.9 and 9.000001 both become 9. If you want to round a float to the nearest integer ( meaning a number with a decimal value of .5 or greater will be rounded up to the next highest integer ) you can do the following:
int(<float object> + 0.5)
This bit of code will cause 9.9 to be 10.4 prior to the integer cast and 9.000001 to be 9.500001. So 9.9 will be truncated to 10 and 9.000001 will be truncated to 9.

Sunday, January 26, 2014

The beginning of all things

Objects

There are some very basic "data types" that python can manipulate. In this post I will discuss different types of numbers. 

Python is an object oriented programming language, meaning that all data (information) in a python program is wrapped in a "container" called an object. Every object consists of three parts, an identity, a type, and a value. So far, you've had experience with identity and value. When you assigned a number to a variable name, the name was the identity and the number was the value. Now we'll discuss the third property type.

The numbers we used in the birth year calculator were whole numbers or "integers". An integer is a "type" of object. If we wanted to use a number with a decimal, we would have to use a "floating point" number. A floating point number or "float" is a different data type. Both represent numbers even though they are different types of objects. 

There is a method for testing an object's type. We can test this by opening our command prompt. (Windows key + r, then type cmd and press "Ok") Type "python" to enter your interpreter.

Create two variables, a and b. Assign a a value of 5, and b a value of 5.0.



Now divide a by 2. Then divide b by 2. Notice that when a is divided by 2 the answer returned is 2, but when b is divided by 2 the answer returned is 2.5.


In order to test the type of an object you can enter type(object name), where object name is the name of the variable you are testing. Do this now with the a and b variables.


Notice that a is a type int object (short for integer), and b is a float type object (short for floating point). Because they are objects of different types they behave differently. Integer objects are only concerned with whole number values, so when two integer values are divided, any non-whole value is discarded. Even though 5 divided by 2 equals 2.5, the decimal is dropped and the answer returned is 2. On the other hand, when the floating point variable, b, is divided by 2 the decimal point is retained even though 2 is an integer.

When performing a calculation on two numbers, the more complex number will determine the 'type' of the result. 

Integer and Integer = Integer

Integer and Float = Float

Float and Float = Float

Object Methods and Properties

Objects often have different properties and methods associated with them. Properties are kind of like additional variables that exist within an object. If you had an object that represented a person, you might have properties like height, weight, and gender. In the case of our two object (int and float), each has different properties. For example, because a is an int object it has a numerator and a denominator property. To access the properties you can simply type a.<property>.

 

However, b is a float object so it doesn't have a numerator or denominator property. Instead it has other properties, real and imag which our int object doesn't have. You can access these properties the same way.

 

In addition to properties, objects can also have "methods". Methods are a type of function that can be used to manipulate or interpret data within an object. Our float object has a "method" called "as_integer_ratio". In order to "call" the method on b type b.as_integer_ratio(). The '()' are how methods and functions are used in python. If you type b.as_integer_ratio without the () and instead of running the method, python will simply tell you that what you are accessing is a method of float object.


Notice that the values returned from the as_integer_ratio method are 5 and 1. This is because in order to represent the value of b as an integer fraction you would use 5/1. If we set b = to 0.5 and run the method again the return values will be 1 and 2 because 0.5 is equal to 1/2.


In order to see all of the properties and methods available for a given object you can type dir(<object name>). Doing this is a good way to get acquainted with objects that you aren't familiar with. For now, just ignore anything with a double underscore. We will discuss these properties and methods later on. For a more detailed description of the properties and methods of an object type help(<object name>).



Objects are a complex subject. I won't go into the intricacies of them all at once. I will try to describe information as it becomes necessary. In this post we've discussed the main types of number objects, next time we will discuss "strings", getting input from a user, and write our first program.