Thursday, August 4, 2011

LPTHW Exercise 5

LPTHW's Exercise 5 is a nice introduction to variables and printing.

I typed the program as is (along with some comments to explain what the program does), and got the expected output.



Extra Credits:

Next I replaced all the variables which start with 'my' such that the names do not contain 'my'. Got that code to also do it's work.



Then I looked up the documentation for String formatting in Python, and learned a few interesting things.
  • Formatting is actually facilitated by a function called '%' in Python String. So basically when we type "hello %s" % name what we are actually doing is calling the '%' function of the String "hello", and giving it the variable 'name' as an argument. If we need to supply only 1 argument, then we can give it a single variable, however, if we need to supply multiple arguments, then we must use a tuple. Like this "hello %s %s" % (first_name, last_name)
  • There are many formatting characters in Python. I checked out the meaning of %r as the exercise mentions. %r will print the String representation of any Python object, by calling the objects repr method. This is interesting. So this is how Python gets a String representation of an object. In Java this is done by invoking the function toString()
Next I created some variables which convert Pounds to Kilograms, and Inches to Centimeters, and that too works properly.


No comments:

Post a Comment