[Tutor] Local vs global

bibi midi bibsmendez at gmail.com
Sat Nov 7 05:03:21 CET 2009


Hi gang,

Although i have read up quite a lot about local and global scope in
functions i still 'suffer' understanding it, i'm afraid. I have this
dragon's realm code modified to my liking or the way i know it. In the
original ebook there is no global variable but i have one on mine. I tried
removing it but i get error variable undeclared or something. It is in the
function choose_Cave.

I know that variables inside a function are local in scope and is gone after
the lifetime of the function, i mean after that function is called. That is
why there is the return statement. What i understand you can access whatever
that function did through the return statement.

I tried assigning the function to a variable outside the function definition
but still it doesnt work. Something like:

x = choose_Cave()
checkCave(x)

I'm slow in this programming thing haha but i want to learn. There are lots
to know in python and how i wish i have all the time. Unfortunately i have
my day job too and first things first. So I'm just managing my time. Below
is the code. Thanks.


#!/usr/bin/env python
# -*- coding: utf-8 -*-

'''
Tutorial book Invent Your Own Computer Games with Python 2nd Edition
Author: Al Sweigart
Chapter 6: Dragon Realm
Filename: dragon.py
Created: 02-Nov-2009
edited: 06-Nov-2009; added functions
'''

import random
import time

location = '/home/bboymen/pyscripts/invent-with-Python/intro.txt'
file = open(location)
intro = file.read()
file.close()

def choose_Cave():
    global choose
    choose = raw_input('choose a cave! (1 or 2): ')
    while choose != '1' and choose != '2':  #(a)
        print('enter 1 or 2 only.')
        choose = raw_input('try again: ')
    return choose

def checkCave(chosenCave):
    print('you approach the cave...')
    time.sleep(2)
    print('it is dark and spooky...')
    time.sleep(2)
    print('a large dragon jumps over you! he open his jaws and....')
    time.sleep(2)
    friendlyCave = random.randint(1, 2)
    if chosenCave == str(friendlyCave):
        print('gives you his treasure!')
    else:
        print('gobbles you down in one bite!')

print(intro)
choose_Cave()
checkCave(choose)
while True:
    ask = raw_input('play again? (y/[N])')
    reply = ['y', 'ye', 'yea', 'yeah', 'yep', 'yes']
    if ask.lower() in reply:
        print "\n", intro
        choose_Cave()
        checkCave(choose)
    else:
        break

print('thanks for playing, goodbye!')


#(a) boolean operator `and` will evaluate 2 boolean values (to its
left and right)
#    and return a single boolean value



-- 
Best Regards,
bibimidi
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20091107/5f864cb4/attachment-0001.htm>


More information about the Tutor mailing list