[Tutor] Local vs global
lie.1296 at gmail.com
Sun Nov 8 19:27:23 CET 2009
bibi midi wrote:
> On Sun, Nov 8, 2009 at 6:20 AM, bibi midi <bibsmendez at gmail.com
> <mailto:bibsmendez at gmail..com>> wrote:
> Thank you all for the helpful insights. I will keep in mind the naming
> rules in Python, so as not to have it in collision with Python's
> The mention to tidy up e.g. "compartmentalize" code is also noted.. I
> agree definitely.
> I'm reworking my code and will post back.
> For reason unknown to me the script dont repeat itself
> when asked if to play again or not no matter what juggling of the
> while/if conditionals i do, the result is the same. What am i
You don't check for whether the answer is 'no'. A single if-statement
branches the code into TWO line of execution, you wanted to have THREE
line of execution (i.e. a 'yes' part, a 'no' part, and an invalid answer
> Also, I'm not sure I'm right in the assignment ans = choose_Cave.
> I code it like so because the assignment ans = choose_Cave()
you declared that `choose` is a global variable.
You should remove this as it adds an unnecessary global variable. Even
if you wish to retain it as a global, you probably should choose a
better name (e.g. current_cave) since the name `choose` has no meaning
outside choose_Cave function.
Also, at the end:
you returned a global variable. Although in some cases it may be
necessary or wanted to return a global variable, you most likely don't
need it since you can always access a global variable from anywhere in a
script. You should make `choose` a local and assign the return value of
choose_Cave() to another name (e.g. current_cave).
> the prompt 'Choose a cave' is repeated when the script is run.
> Dont want this. I tested this when run in ipython.
> I dont know if there is a way to just retrieve the return value to a
> variable AND not run the whole function i mean in the case of
> ans = choose_Cave(). Would love to hear your expert insights by return.
A function can be run multiple times, and its return value may be
different every time it is run (in fact if the return value is always
the same there is no point in using function). "accessing the return
value and not run the function" doesn't make sense as it is unclear what
you're wanting to access. What you wanted is to access the latest return
value of choose_Cave, which means you want to store the return value of
choose_Cave in a variable (i.e. current_cave = choose_Cave() or ans =
An alternative would be to store the latest return value in a global
variable, but I strongly recommend against this as global variable is
More information about the Tutor