[Tutor] Help please!

Steven D'Aprano steve at pearwood.info
Fri Dec 14 23:04:36 CET 2012


On 02/12/12 12:37, Jack Little wrote:
> Hi Tutor,
> I'm getting this error
>
> Traceback (most recent call last): File "C:\Users\Jack\Desktop\python\g.py",
>line 45, in<module>  path_1pt1()
> NameError: name 'path_1pt1' is not defined


Names need to be defined before they are used. Code needs to be indented to
be inside a function, if it is not indented then it is considered to be part
of the "top level" code that runs immediately.

So you begin a new function, simpstart:


> def simpstart():
>    global ammo
>    global health
>    global tech_parts
>    global radio_parts

By the way, you can consolidate those four lines to one:

     global ammo, health, tech_parts, radio_parts


But here you lose the indentation, so Python considers the following to
be "top level" code and executes it immediately:

> print "You awake in a haze. A crate,a door and a radio."
> g1 = raw_input("Which do you choose  ")

Questions in English should end with a question mark, or people will
consider you ignorant and illiterate. Unless you are a famous poet
or artist, in which case they will fawn over how transgressive you are.


> if g1 == "CRATE" or g1 == "Crate" or g1 == "crate":

What if they type "cRAtE" or "crATE"?

Much simpler to do this:

if g1.lower() == "create":

By the way, you will find programming much, much simpler if you always
use meaningful variable names. "g1"? What does that mean? A better name
would be something like "user_response", or even just "response".

So, skipping ahead, we come to this bit:

> elif g2 == "NORTH" or g2 == "North" or g2 == "north":
>          path_1pt1()

Again, this is better written as "if g2.lower() == 'north':".

At this point, Python then tries to call the path_1pt function, but it
hasn't been defined yet. So it gives you a NameError.

How do you fix this? Simple: this entire block of code needs to be
indented level with the global declarations at the start of simstart.

(Fixing this error may very well reveal further errors. Good luck!)

Another comment:


> #A Towel Production
> # APOC
> #-------
> global ammo1
> global ammo2
> global ammo3
> global health
> global tech_parts
> global exp
> global radio_parts

These seven global lines don't do anything. They are literally pointless. One
of the mysteries to me is why Python allows global declarations outside of
functions, but these lines literally do nothing at all except fool the reader
(you!) into thinking that they do something. Get rid of them.


> ammo1=10
> ammo2=0
> ammo3=0

I note that you have three variables, "ammo1" through "ammo3", but in the
simpstart function, you declare a global "ammo".




-- 
Steven


More information about the Tutor mailing list