Wednesday, August 31, 2011

LPTHW - Exercise 8

Completed exercise 8.

Nothing much to report in terms of thought process, etc for this exercise.

formatter = "%r %r %r %r"
print formatter % (1, 2, 3, 4)
print formatter % ("one", "two", "three", "four")
print formatter % (True, False, False, True)
print (formatter, formatter, formatter, formatter)
print formatter % (
"I had this thing.",
"That you could type up right.",
"But it didn't sing.",
"So I said goodnight."
)
view raw ex8.py hosted with ❤ by GitHub

Thursday, August 4, 2011

LPTHW - Exercise 7

In exercise 7, we learn a bit more about printing. I typed the program, added some comments to explain what it does and got it to work.

# print a string
print "Mary had a little lamb."
# print a string that has formatting characters in it
print "Its fleece was white as %s." % 'snow'
# print a string
print "And everywhere that Mary went."
# print a string and print it 10 times
print "." * 10 # what'd that do?
#declare a String which is a single character long
end1 = "C"
end2 = "h"
end3 = "e"
end4 = "e"
end5 = "s"
end6 = "e"
end7 = "B"
end8 = "u"
end9 = "r"
end10 = "g"
end11 = "e"
end12 = "r"
# watch that comma at the end. try removing it to see what happens
#The comma prevents a new line from being printed
print end1 + end2 + end3 + end4 + end5 + end6,
#concatenate the specified Strings and print the result
print end7 + end8 + end9 + end10 + end11 + end12
view raw ex7.py hosted with ❤ by GitHub


Some observations:
  • Ending a print statement with a ',' as we see on line 29, prevents a newline from being printed
  • Multiplying a String, concatenates the String with itself, that many times (as seen on line 11)

LPTHW - Exercise 6

In the last exercise, we learned about variables and also introduced String formatting. In this exercise, we learn more about Strings and text.

First, I typed the program as is, and got the expected output.

#assign a String to the variable x. The String is a formatted String
#where we replace %d with 10
x = "There are %d types of people." % 10
#assign the variable 'binary' with a value which is a String 'binary'
binary = "binary"
#
do_not = "don't"
y = "Those who know %s and those who %s." % (binary, do_not)
print x
print y
print "I said: %r" % x
print "I also said: '%s'." % y
hilarious = False
joke_evaluation = "Isn't that joke so funny?! %r"
print joke_evaluation % hilarious
w = "This is the left side of..."
e = "a string with a right side."
print w + e
view raw ex6.py hosted with ❤ by GitHub


Extra Credit:

Next, I commented the code, and also counted the number of times we put a String inside a String (it is indeed four times).

#assign a String to the variable x. The String is a formatted String
#where we replace %d with 10
x = "There are %d types of people." % 10
#assign the variable 'binary' with a value which is a String 'binary'
binary = "binary"
#assign a String to the variable do_not
do_not = "don't"
#assign a String to the variable y. This is a formatted String which has
#two replecement variables
#This is the first place where a String is put inside a String
y = "Those who know %s and those who %s." % (binary, do_not)
#print the value of the variable x
print x
#print the value of the variable y
print y
#print the specified String which also contains a replacement
#In this case we use the %r formatting character, which will
#be replaced witht the String representation of the specified object
#This is the second place where a String is put inside a String
print "I said: %r" % x
#print the specified String, which contains a replacement value
#This is the third place where a String is put inside a String
print "I also said: '%s'." % y
#set the variable 'hilarious' to the boolean value False
hilarious = False
#Set the variable 'joke_evaluation' to the String containing a replacement
#value. We do not specify the replacement here. It will be specified
#when we use the String
joke_evaluation = "Isn't that joke so funny?! %r"
#print the value of the String 'joke_evaluation' and use the value of
#the String 'hilarious' as a replacement
#This is the fourth place where a String is put inside a String
print joke_evaluation % hilarious
#assign a String value to the variable 'w'
w = "This is the left side of..."
#assign a String value to the variable 'e'
e = "a string with a right side."
#concatanate w and e and print the result
print w + e
view raw ex6_b.py hosted with ❤ by GitHub


Some Observations:
  • When we concatenate multiple Strings a space character is not added between them, the way print adds it, when we try to print multiple Strings. So if we want to print multiple Strings without spaces between them, then we should concatenate them with the + operator and print the concatenated result.
Some questions:

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.

my_name = 'Zed A. Shaw'
my_age = 35 # not a lie
my_height = 74 # inches
my_weight = 180 # lbs
my_eyes = 'Blue'
my_teeth = 'White'
my_hair = 'Brown'
print "Let's talk about %s." % my_name
print "He's %d inches tall." % my_height
print "He's %d pounds heavy." % my_weight
print "Actually that's not too heavy."
print "He's got %s eyes and %s hair."
print "His teeth are usually %s depending on the coffee." % my_teeth
# this line is tricky, try to get it exactly right
print "If I add %d, %d, and %d I get %d." % (my_age, my_height, my_weight, my_age + my_height + my_weight)
view raw ex5_a.py hosted with ❤ by GitHub


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.

name = 'Zed A. Shaw'
age = 35 # not a lie
height = 74 # inches
weight = 180 # lbs
eyes = 'Blue'
teeth = 'White'
hair = 'Brown'
print "Let's talk about %s." % name
print "He's %d inches tall." % height
print "He's %d pounds heavy." % weight
print "Actually that's not too heavy."
print "He's got %s eyes and %s hair."
print "His teeth are usually %s depending on the coffee." % teeth
# this line is tricky, try to get it exactly right
print "If I add %d, %d, and %d I get %d." % (age, height, weight, age + height + weight)
view raw ex5_b.py hosted with ❤ by GitHub


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.


kg_to_pound = 2.20462262185
inch_to_cm = 2.54
name = 'Zed A. Shaw'
age = 35 # not a lie
height = 74 # inches
height_in_cm = height * inch_to_cm
weight = 180 # lbs
weight_in_kg = weight/kg_to_pound
eyes = 'Blue'
teeth = 'White'
hair = 'Brown'
print "Let's talk about %s." % name
print "He's %d inches tall." % height
print "He's %d cm tall." % height_in_cm
print "He's %d Pounds heavy." % weight
print "He's %d Kilograms heavy." % weight_in_kg
print "Actually that's not too heavy."
print "He's got %s eyes and %s hair."
print "His teeth are usually %s depending on the coffee." % teeth
# this line is tricky, try to get it exactly right
print "If I add %d, %d, and %d I get %d." % (age, height, weight, age + height + weight)
view raw ex5_c.py hosted with ❤ by GitHub

Wednesday, August 3, 2011

LPTHW - Exercise 4

Starting with exercise 4, where we learn about variables. I typed in the code, and got an error when I tried to run it.

#THIS CODE HAS AN ERROR
cars = 100
space_in_a_car = 4.0
drivers = 30
passengers = 90
cars_not_driven = cars - drivers
cars_driven = drivers
carpool_capacity = cars_driven * space_in_a_car
average_passengers_per_car = passengers / cars_driven
print "There are", cars, "cars available."
print "There are" only", drivers, "drivers available."
print "There will be", cars_not_driven, "empty cars today."
print "We can transport", carpool_capacity, "people today."
print "We have", passengers, "to carpool today"
print "We need to put about", average_passengers_per_car, "in each car."


Error:
File "ex4.py", line 11
print "There are" only", drivers, "drivers available."
^
SyntaxError: invalid syntax

Solution: The problem is the double quote after 'are'

Here is the correct solution:

#Define a variable called cars and give it the integer value 100
cars = 100
#Define a variable called space_in_a_car a nd give it the floating point value 4.0
space_in_a_car = 4.0
#Define a variable called drivers, and give it the integer value 30
drivers = 30
#Define a variable called passengers, and give it the integer value 90
passengers = 90
#Define a variable called cars_not_driven, and compute it as the difference between cars and drivers
cars_not_driven = cars - drivers
#Define a variable called cars_driven and assign to it the value of the variable drivers
cars_driven = drivers
#Define a variable called carpool_capacity and compute it as the product of the values of variables, cars_driven and space_in_a_car
carpool_capacity = cars_driven * space_in_a_car
#Define a variable called average_passengers_per_car and compute it as passengers divided by cars_driven
average_passengers_per_car = passengers / cars_driven
#print the number of cars available
print "There are", cars, "cars available."
#print the number of drivers available
print "There are only", drivers, "drivers available."
#print the number of empty cars today
print "There will be", cars_not_driven, "empty cars today."
#print the number of people we can transport today
print "We can transport", carpool_capacity, "people today."
#print the number of passengers we have for carpooling today
print "We have", passengers, "to carpool today."
#print the average passengers we can place per car
print "We need to put about", average_passengers_per_car, "in each car."
view raw ex4.py hosted with ❤ by GitHub


Here is the output:

There are 100 cars available.
There are only 30 drivers available.
There will be 70 empty cars today.
We can transport 120.0 people today.
We have 90 to carpool today
We need to put about 3 in each car.


Questions:
  1. An interesting observation : When we give multiple values to print (separated by commas), a space is automatically put in between them. This is really nice, but what if we do not want to the space?

Observations:
  1. In python we do not have to give the type of variables (because Python is dynamically typed), and we do not need to use any special keyword like var, or def before declaring a variable,. This is in contrast to other languages which normally require something before a variable name.

Extra Credit:

The error described on the page:
Traceback (most recent call last):
File "ex4.py", line 8, in
average_passengers_per_car = car_pool_capacity / passenger
NameError: name 'car_pool_capacity' is not defined
This means that a variable of the name 'car_pool_capacity' had not yet been defined. This could happen if the author either forgot to define the variable, or did a typo when defining it. In this case it looks like a typo because the actual variable is 'carpool_capacity'.

Why do we use 4.0 instead of 4 ?
4.0 is a floating point number, while 4 is an integer. Floating point numbers can represent fractions, while integers cannot.

With some experimentation with Python, I realized that if we do operations with all integers, then the result will also be an integer. If the operation of a division operation and the result is actually a fraction, then it will be truncated to yield an integer.

However, if even one of the numbers is a floating point number, then the rest will be promoted to floating point numbers to yield a floating point number.

i = 4
j = 3
i/j
answer: 1

i = 4.0
j = 3
i/j
answer: 1.3333

i = 4
j = 3.0
i/j
answer: 1.3333

Tuesday, August 2, 2011

LPTHW - Exercise 3

# The meaning of operators in Python
# + plus Addition
# - minus Subtraction
# / slash Division
# * asterisk Multiplication
# / percent Also modulus operator, which returns the remainder from division
# < less-than Returns true if the operans on the LHS is less than RHS
# > greater-than Returns true if the operand on the LHS is greater than RHS
# <= less-than-equal Returns true if the operand on the LHS is less than or equal to RHS
# >= greater-than-equal Returns true if the operand on the LHS is greater than or equal to the RHS
print "I will now count my chickens:"
print "Hens", 25 + 30 / 6
print "Roosters", 100 - 25 * 3 % 4
print "Now I will count the eggs:"
print 3 + 2 + 1 - 5 + 4 % 2 - 1 / 4 + 6
print "Is it true that 3 + 2 < 5 - 7?"
print 3 + 2 < 5 - 7
print "What is 3 + 2?", 3 + 2
print "What is 5 - 7?", 5 - 7
print "Oh, that's why it's False."
print "How about some more."
print "Is it greater?", 5 > -2
print "Is it greater or equal?", 5 >= -2
print "Is it less or equal?", 5 <= -2
view raw gistfile1.txt hosted with ❤ by GitHub

Stuff I learned:
  • Operator precedence
  • The print function can take multiple arguments, separated by commas

Monday, August 1, 2011

LPTHW - Exercise 2

I did exercise 2 from the book.

# A comment, this is so you can read your program later.
# Anything after the # is ignored by Python.
print "I could have code like this." # and the comment after is ignored
# You can also use a comment to "disable" or comment out a piece of code:
# print "This won't run."
print "This will run."


Extra Credit:
  • I was right about the '#' character. It is used to comment out single lines
  • Read the file backwards comparing it to the original program... no errors so far
  • I read what I typed out aloud, and still no errors...

LPTHW - Exercise 1

I completed exercise 1. The code is embedded below.

print "Hello World!"
print "Hello Again"
print "I like typing this."
print "This is fun."
print 'Yay! Printing.'
print "I'd much rather you 'not'."
print 'I "said" do not touch this.'
view raw gistfile1.txt hosted with ❤ by GitHub


Stuff I learned:
  1. In Python we use the 'print' function to print to the console
  2. In Python function calls need not have () like in Java
  3. In Python we use the '#' character to comment a single line. The C style comment '//' does not work in Python
  4. We do not have to end a statement with a ';' or any delimiter in Python
  5. Python Strings can be delimited by double quotes as well as single quotes
  6. A double quoted string can contain single quotes
  7. It is not compulsory to have a main method in Python

LPTHW Exercise 0

In this exercise, we install Python. I am using Ubuntu 10.04, so I moved straight to the "Installing on Linux" section.
  1. I already have GEDIT
  2. Changed the defaults in Gedit as suggested in the book
  3. Found my terminal program
  4. Not yet putting my terminal in the dock
  5. Opened my terminal program
  6. I already have Python 2.6.5 installed
  7. Hit CTRL-D and I am out of the Python shell
  8. I am at the command prompt now
  9. Made a directory
  10. Changed into it
  11. Created a README.txt file in the directory
  12. Went to the terminal and back to the browser using just the keyboard
  13. I am back in the terminal and can see the directory. I also listed it's contents
Besides the things suggested in the book, I am planing to make this a git repository. I will either push all the exercises to GitHub, or paste them in Gists.

Hello Python

I did a little work in Python a very long time back, and grasped some key concepts of Python. Since then I have forgotten a lot of the stuff I learned back then, and feel like I need to refresh my knowledge.

What better time to refresh the knowledge than before Pycon 2011, Pune.

I just enrolled in the Introduction to Python online course at DIY Computer Science. This course is based on Zed Shaw's book "Learn Python the Hard Way 2.0".

This course is based on a peer learning model. Everyone who registers must maintain a blog which will serve as their learning journal (that is what this blog will be). The course consists of some reading and 52 exercises. Participants do the exercises and blog about their notes , reflections, and code. Then they submit their blog posts in the appropriate activity sections. If anyone has questions, they can ask them in the course forum.

So that's it. I am quite excited to refresh my Python skills...