kassold
kassold

Reputation: 469

Zed Shaw's Learn Python the Hard way Tutorial

I'm new to programming and currently going through the exercises in Zed Shaw's Python book. In Zed's Ex41, there is this function:

def runner(map, start):
     next = start

     while True:
         room = map[next]
         print "\n-------"
         next = room()

My question is, why did he have to assign 'start' to the variable 'next' when he could have used 'start' straight away? Why didn't he just do this?

def runner(map, start):


     while True:
         room = map[start]
         print "\n-------"
         start = room()

Because this function also seem to work. Thanks

Upvotes: 4

Views: 4239

Answers (4)

bukzor
bukzor

Reputation: 38502

He didn't have to, but did for naming-style considerations.

Upvotes: 0

unutbu
unutbu

Reputation: 880229

I think it was done for readability. In the programmer's mind, start is supposed to represent the start of something. next was presumably supposed to represent the next item.

You are correct that the code could be shortened, but it mangles the meaning of start.

Note that in current versions of Python (2.6 or later), next is a built-in function, so it's no longer a good idea to name a variable next.

Upvotes: 10

escargot agile
escargot agile

Reputation: 22389

I guess it's just for readability. When writing code, you should always keep in mind that variables (and also functions, classes etc) should always have meaningful names, otherwise reading your code will be a nightmare. The meaning of the variable in the loop is to hold the next item, not the start item.

Upvotes: 2

Alex Vidal
Alex Vidal

Reputation: 4108

The second example works, yes, but he's trying to write a Python tutorial style book, and I think the first one is much more clear about exactly what's going on. start as a variable name loses meaning when it's no longer the actual start, but instead the next room that we're going into.

Upvotes: 18

Related Questions