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.



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:



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

3 comments:

  1. Great Explanation to the "Study Drill" questions. Straight to the point and really helpful!!!

    ReplyDelete
  2. Thank you for your explains of Study Drill!

    ReplyDelete
  3. I count myself lucky to be able to use your book as my first introduction to python.

    ReplyDelete