Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Zed Shaw's Learn Python the Hard way Tutorial

Tags:

python

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

like image 676
kassold Avatar asked Nov 27 '22 10:11

kassold


2 Answers

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.

like image 130
Alex Vidal Avatar answered Dec 05 '22 16:12

Alex Vidal


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.

like image 38
unutbu Avatar answered Dec 05 '22 16:12

unutbu