new to python - trouble calling a function from another function

Ulrich Eckhardt eckhardt at satorlaser.com
Thu Aug 5 12:35:50 CEST 2010


Brandon McCombs wrote:
> I'm building an elevator simulator for a class assignment. I recently
> ran into a roadblock and don't know how to fix it. For some reason, in
> my checkQueue function below, the call to self.goUp() is never executed.
[...]
> sorry about the formatting

While I can certainly forgive you the formatting (my problem is rather that
you didn't reduce the code to the smallest possible example), Python wont.
Python is a language where whitespace is significant and can subtly change
the meaning of your code.

Example:

> for i in range(0,self.newPassengers):
> self.passengerList.append(self.passengerWaitQ.pop())
> self.goUp()

The formatting here is completely removed, but there are two conceivable
ways this could be formatted:

# variant 1
for i in range(0,self.newPassengers):
    self.passengerList.append(self.passengerWaitQ.pop())
    self.goUp()

#variant 2
for i in range(0,self.newPassengers):
    self.passengerList.append(self.passengerWaitQ.pop())
self.goUp()

Someone already mentioned PEP 8 (search the web!). These PEPs could be
called the standards governing Python behaviour, and PEP 8 actually defines
several things concerning the formatting of sourcecode. Apply it unless you
have a good reason not to.


Further, you should run Python with "-t" as argument on the commandline.
This will give you warnings when it encounters inconsistent tab/spaces
usage. This can make a difference.

Example:

    #variant 3
    for i in range(0,self.newPassengers):
        self.passengerList.append(self.passengerWaitQ.pop())
<TAB>self.goUp()

If your editor is set to four spaces per tab, this will look like variant 2,
with 8 spaces it will look like variant 1. I don't know (and don't care,
since PEP-8 mandates four spaces) which interpretation Python actually
uses.


Lastly, you can simplify your check_queue() function. First, determine the
number of free places inside the elevator. Then, you simply append that
many passengers from the waiting list to the passenger list:

  free = MAX_CAPACITY - len(self.passengers)
  new_passengers = self.passenger_wait_queue[:free]
  self.passenger_wait_queue = self.passenger_wait_queue[free:]
  self.passengers += new_passengers

This uses the fact that list indices are automatically truncated to a valid
range, so requesting the elements 0 to 10 from a 5-element list will only
yield those five elements, not raise an exception. It's up to you though
which version is clearer to you. I would perhaps bail out if "free == 0"
and then also not call go_up() lateron.


Cheers and good luck!

Uli

-- 
Sator Laser GmbH
Geschäftsführer: Thorsten Föcking, Amtsgericht Hamburg HR B62 932




More information about the Python-list mailing list