I've been trying to figure this out for a few days, and my teacher can't really answer my question, as he is just as stumped as I am.

Python is supposed to be pass by reference, but I keep getting pass by value when it comes to returning a bool variable from a function, or even changing the status of a bool variable in an if statement in main

I have tried to apply many different solutions trying to get a bool variable to change but no matter what I do it never changes. Is there a reason for this, or something I'm not catching onto? I know with C++ you have to use & to pass by reference anything in a function, but since Python is supposedly pass by reference as default, I know of no operators to force the variable into a reference variable.

I have tried 3 approaches to this solution:
The first being to pass the bool variable into a function and test to see its status, and depending on the nature of the beast, it may or may not change, and if the status of the variable changes, it's done inside the function, and then the variable is returned.

The second approach is just assigning the bool variable a value depending on the outcome of the nature of the beast in an if statement in main

The third approach I've done is just to return the value of the variable (True or False), and in main() I assign the bool variable to that function, so theoretically the bool variable would catch the value of the bool function.

None of these works
I ran into this same exact problem when trying to make a tic-tac-toe game in python a few weeks ago - it would only pass by value...

I'm stumped, and if I can't get this to work, I have to down play this text game and make it more automated, but I'd rather see it as interactive as possible. If someone can point me in the right direction it'd be much appreciated.

This is my code:
1st Approach - returning a value or bool variable from a function

result = checkAnswer("C", userAnswer)
    if(result):
    #if answer is incorrect, display message as such
        wrongAnswer()
        #choose what limb to cut off teacher
        choice = chooseLimb()
        #check to make sure limb isn't already hacked off
        checkLimb(armRight)
        if(checkLimb(armRight)):
            print "That limb has already been hacked off!"
        #test new value of armRight   
        print "Value of armRight is now",armRight

Note ** when running this code (and the rest I hadn't posted because it's irrelevant to this question) I purposely choose the wrong answer, and choose a limb to cut off to force the value to change

the new value (last line of above code) doesn't change value
calling the function checkLimb(limb) is as follows:

# CHECK LIMB #
def checkLimb(limb):
    if limb == True:
        limb = False
        return limb  # or just returning false - same outcome - no change
    else:
        return True

2nd Approach: - assigning the bool variable to bool function

if(result):
        #display wrong answer message
        wrongAnswer()
        #choose what limb teacher loses
        choice = chooseLimb()        
        result = checkLimb(armRight)
        #test value of bool
        print "Value of armRight is ",armRight

the value of the bool stays true again
I have tried assigning the arguement passed into the function (arguement of bool value, of course) and returning the arguement, as well as returning False instead of the arguement, and the value stays true

3rd Approach: - assigning value to bool variable in if statement in main()

#test for right answer to a question
result = checkAnswer("C", userAnswer)    
    if(result):
        #display wrong answer message
        wrongAnswer()
        #choose what limb to lose
        choice = chooseLimb()        
        if choice == 1 and armRight == True:
            armRight = False
            print "The teacher has lost his right arm"
        print "Value of armRight is ",armRight

Yet the value of armRight stays true

The armRight variable is declared and assigned to True before it is called for anything.

armRight = True

It never changes ><

Any ideas?

Recommended Answers

All 10 Replies

The armRight variable is declared and assigned to True before it is called for anything.

I'm quite sleepy, so excuse me if I'm way off here, but is armRight declared within the global scope of the script? If so, then you need to state global armRight within your function so that when you modify armRight within the function, it does in fact change the global armRight.

And when you get into passing within Python, I find it tends to get a lot more complicated than the straight-forward ways of passing in C++. It's kind of a hybrid I guess, but you do get used to the way if works and if you use Python long enough you structure your code work quite seamlessly with this part of the language.

This can sum it up fairly well though:
"If using objects' methods within a called function, a variable is considered “passed by reference” – it is modified out of the function’s scope. If using assignment on a mutable object, it is created a-new within the function, and the global value isn’t modified."

You can take a peek at a short but to-the-point snippet about Python's passing of arguments here.

actually there are 5 bool variables -
armRight
armLeft
legRight
legLeft
head

these are declared and assigned a true value in def: main() so they're not global. I was always taught using global variables is a bad idea for most cases? def main(): calls all the functions that use the variables, so in theory those variables should still change value when being returned. For the arguements in checkLimb I only pass one of those 5 variables at a time, so the formal parameter is just limb - so the function is checkLimb(limb) - that way I don't have to write a check function for each variable.

I tried to do this globally after your suggestion, but I keep getting syntactical errors when I put global in front of anything - including the formal parameter used in checkLimb(limb) in the definition itself

def checkLimb(limb):
    if limb == True:
        limb = False
        return True
    else:
        return False

so basically it checks to see if the limb is still attached to the teacher, and if it is (true) then 'limb' is changed to false and returns true - verifying that the limb was there so that the code can hack off the teacher's limb - and the next time the limb is checked it'll come back as false, which will prompt the user to re-select what limb to hack off in the next function.

I know I could also remove the limb removed from the menu, but that would also depend on getting the variable to change.

when I try to use global limb in the function python yells at me. Is it too ambiguous for python to handle?

I'm reading that strings and integers when passed as an arguement are by value but it's confusing because some of those will pass by reference and others (always ones I'm trying to do myself, never ones thru the book at school, or course) by value only.

Dictionaries and lists and tuples are something that I'm not familiar with yet in python. Are dictionaries kind of like a library? In any case, I still can't get this to work right. If you want I can put up all my code, but I"m trying to limit the amount of reading to make it easier - so I'm posting only what I think is relevant code

You haven't recieved many answers, and probably won't because your examples are incomplete. You are obviously doing something in the code that is not posted that alters the result. Take a look at the following code that is a complete program that can be run. It shows that your contention does not hold up, at least as far as I can tell from what has been posted. You may be re-defining variables or it may be a scope problem, but there is no way to tell from the snippets that were posted. Also, this bit of code

result = checkAnswer("C", userAnswer)
    if(result):
    #if answer is incorrect, display message as such
        wrongAnswer()

will not even run because of improper indents.

def change_bool(bool_arg):
   bool_arg = not bool_arg
   print "in first function", bool_arg     ## prints 'False'

def change_2():
   test_1 = False
   print "in 2nd function", test_1     ## prints 'False'

test_1 = True
change_bool(test_1)
print "first", test_1     ##(prints 'True')
change_2()
print "second", test_1     ##(prints 'True')

eh the indents being off was just me editing the text - typo - I will post all code I have so far on this project.

if there are any indents that are off in this, it is the forums fault I swear! lol I copied and pasted directly into here...

also, to make it easy on you guys, the questions are different, but the logic after the questions is all the same. It's just copied and pasted after each question.

The algorithm:
User is asked a question
User enters question in
Question is compared to actual answer
If the answer is correct, the correct answer is tallied into variable
If the answer is not correct
-- User chooses limb for robot to hack off
-- Program checks to see if limb is available (bools....)
--If not availbe - user re-prompted
-- If available - limb is hacked off, limb set to opposite bool value
-- Robot rage increases

That's roughly as far as I've gotten with this, so not all modules are written yet for what is promised in the description, but this is everything and it runs fine for what it is, with the exception of the bool values not changing after returning from a function. I can't continue because I'm stuck on the bools.

I've re-written the program so that the limb removal process is automated and everything works beautifully, but I still want to know what I'm doing wrong here so that in the future I know how to do this. This isn't the first game I've tried to write in python where I've needed to change a bool value from a function and it refuses to flip.

def main():
    ######################## DECLARE VARIABLES #####################
    armRight = False
    armLeft = False
    legLeft = False
    legRight = False
    head = False
    correctAns = 0
    angerRate = 0

    

    ######################## DISPLAY INTRO #########################
    print "                        Mr. Taylor vs The BattleBot! v1.0"
    print
    print "In order to prove yourself worth sparing to the universe, you must answer the following questions correctly."
    print "Failure to do so will result in the teacher losing a limb by the battle bot!"
    print "Your teacher's hard work is at stake!"
    print
    print "Each incorrect answer will raise the BattleBot's hatred towards you, the student!"
    print "After the BattleBot loses his temper, he will stab you!"
    print
    print "<BattleBot> Good luck, earthling.  You are going to need it..."
    print
    print "                   *ALL ANSWERS MUST BE IN CAPITAL LETTERS!*"
    print
    ################### QUESTION 1 ######################
    userAnswer = raw_input("What is not a valid variable type? \n"
                           "A. integer \n"
                           "B. string \n"
                           "C. function  \n"
                           "D. double \n"
                           "Your Answer: ")
    if userAnswer != "C":
        choice = chooseLimb()
        while(choice != 1 and choice != 2 and choice != 3 and choice != 4 and choice != 5):
            choice = chooseLimb()
        checkLimb(choice, armRight, armLeft, legRight, legLeft)
        if not(checkLimb):
            choice = reChooseLimb()
            while(choice != 1 and choice != 2 and choice != 3 and choice != 4 and choice != 5):
                chooseLimb()
        loseLimb(choice, armRight, armLeft, legRight, legLeft, head)
        angerRate+=1
    else:
        correctAns+=1
        print
        
    ################### QUESTION 2 ######################
    userAnswer = raw_input("What must be called in order for a Python script to execute? \n"
                           "A. The executable file \n"
                           "B. A minimum of one variable \n"
                           "C. The main function \n"
                           "D. namespace std; \n"
                           "Your Answer: ")
    if userAnswer != "C":
        choice = chooseLimb()
        while(choice != 1 and choice != 2 and choice != 3 and choice != 4 and choice != 5):
            choice = chooseLimb()
        checkLimb(choice, armRight, armLeft, legRight, legLeft)
        if not(checkLimb):
            choice = reChooseLimb()
            while(choice != 1 and choice != 2 and choice != 3 and choice != 4 and choice != 5):
                chooseLimb()
        loseLimb(choice, armRight, armLeft, legRight, legLeft, head)
        angerRate+=1
    else:
        correctAns+=1
        print
        
    ################### QUESTION 3 ######################
    userAnswer = raw_input("What is a string variable? \n"
                           "A. A toy for the cat \n"
                           "B. A variable containing characters \n"
                           "C. A random ASCII value \n"
                           "D. B and C \n"
                           "Your Answer: ")
    if userAnswer != "B":
        choice = chooseLimb()
        while(choice != 1 and choice != 2 and choice != 3 and choice != 4 and choice != 5):
            choice = chooseLimb()
        checkLimb(choice, armRight, armLeft, legRight, legLeft)
        if not(checkLimb):
            choice = reChooseLimb()
            while(choice != 1 and choice != 2 and choice != 3 and choice != 4 and choice != 5):
                chooseLimb()
        loseLimb(choice, armRight, armLeft, legRight, legLeft, head)
        angerRate+=1
    else:
        correctAns+=1
        print
        
    ################### QUESTION 4 ######################
    userAnswer = raw_input("What is the purpose of a function? \n"
                           "A. Readability \n"
                           "B. Quicker Programming \n"
                           "C. To store arrays \n"
                           "D. A and B \n"
                           "Your Answer: ")
    if userAnswer != "D":
        choice = chooseLimb()
        while(choice != 1 and choice != 2 and choice != 3 and choice != 4 and choice != 5):
            choice = chooseLimb()
        checkLimb(choice, armRight, armLeft, legRight, legLeft)
        if not(checkLimb):
            choice = reChooseLimb()
            while(choice != 1 and choice != 2 and choice != 3 and choice != 4 and choice != 5):
                chooseLimb()
        loseLimb(choice, armRight, armLeft, legRight, legLeft, head)
        angerRate+=1
    else:
        correctAns+=1
        print
        
    ################### QUESTION 5 ######################
    userAnswer = raw_input("What is the default \'pass by\' in Python? \n"
                           "A. Value \n"
                           "B. Cost \n"
                           "C. Reference \n"
                           "D. None \n"
                           "Your Answer: ")
    if userAnswer != "C":
        choice = chooseLimb()
        while(choice != 1 and choice != 2 and choice != 3 and choice != 4 and choice != 5):
            choice = chooseLimb()
        checkLimb(choice, armRight, armLeft, legRight, legLeft)
        if not(checkLimb):
            choice = reChooseLimb()
            while(choice != 1 and choice != 2 and choice != 3 and choice != 4 and choice != 5):
                chooseLimb()
        loseLimb(choice, armRight, armLeft, legRight, legLeft, head)
        angerRate+=1
    else:
        correctAns+=1
        print
        
    ################### QUESTION 6 ######################
    userAnswer = raw_input("Who invented Python? \n"
                           "A. Fredrick Neitzsche \n"
                           "B. Guido Van Rossum \n"
                           "C. Edward Scissorhands \n"
                           "D. Marty Friedman \n"
                           "Your Answer: ")
    if userAnswer != "B":
        choice = chooseLimb()
        while(choice != 1 and choice != 2 and choice != 3 and choice != 4 and choice != 5):
            choice = chooseLimb()
        checkLimb(choice, armRight, armLeft, legRight, legLeft)
        if not(checkLimb):
            choice = reChooseLimb()
            while(choice != 1 and choice != 2 and choice != 3 and choice != 4 and choice != 5):
                chooseLimb()
        loseLimb(choice, armRight, armLeft, legRight, legLeft, head)
        angerRate+=1
    else:
        correctAns+=1
        print
        
    ################### QUESTION 7 ######################
    userAnswer = raw_input("What type of language is Python? \n"
                           "A. Low-Level \n"
                           "B. High-Level \n"
                           "C. Scripting \n"
                           "D. Award-Winning \n"
                           "Your Answer: ")
    if userAnswer != "C":
        choice = chooseLimb()
        while(choice != 1 and choice != 2 and choice != 3 and choice != 4 and choice != 5):
            choice = chooseLimb()
        checkLimb(choice, armRight, armLeft, legRight, legLeft)
        if not(checkLimb):
            choice = reChooseLimb()
            while(choice != 1 and choice != 2 and choice != 3 and choice != 4 and choice != 5):
                chooseLimb()
        loseLimb(choice, armRight, armLeft, legRight, legLeft, head)
        angerRate+=1
    else:
        correctAns+=1
        print
        
    ################### QUESTION 8 ######################
    userAnswer = raw_input("Passing a memory address through a function is knowns as: \n"
                           "A. Pass-By-Reference \n"
                           "B. Pass-By-Value \n"
                           "C. Pass-By-Cost \n"
                           "D. This cannot be done \n"
                           "Your Answer: ")
    if userAnswer != "A":
        choice = chooseLimb()
        while(choice != 1 and choice != 2 and choice != 3 and choice != 4 and choice != 5):
            choice = chooseLimb()
        checkLimb(choice, armRight, armLeft, legRight, legLeft)
        if not(checkLimb):
            choice = reChooseLimb()
            while(choice != 1 and choice != 2 and choice != 3 and choice != 4 and choice != 5):
                chooseLimb()
        loseLimb(choice, armRight, armLeft, legRight, legLeft, head)
        angerRate+=1
    else:
        correctAns+=1
        print
        
    ################### QUESTION 9 ######################
    userAnswer = raw_input("What is the best type of loop to use for counting? \n"
                           "A. Counter Loop \n"
                           "B. Do While Loop \n"
                           "C. For Loop \n"
                           "D. Bubble-Sort Method \n"
                           "Your Answer: ")
    if userAnswer != "C":
        choice = chooseLimb()
        while(choice != 1 and choice != 2 and choice != 3 and choice != 4 and choice != 5):
            choice = chooseLimb()
        checkLimb(choice, armRight, armLeft, legRight, legLeft)
        if not(checkLimb):
            choice = reChooseLimb()
            while(choice != 1 and choice != 2 and choice != 3 and choice != 4 and choice != 5):
                chooseLimb()
        loseLimb(choice, armRight, armLeft, legRight, legLeft, head)
        angerRate+=1
    else:
        correctAns+=1
        print
        
    ################### QUESTION 10 ######################
    userAnswer = raw_input("What will this code do? \n"
                           "Number = input_stream(openFile(\"Numbers.txt\"(\"Please enter a number: \")\") \n"
                            "A. Input a number from a text file \n"
                            "B. Input a number from a user \n"
                            "C. User inputs a number and is stored to a flat file \n"
                            "D. Absolutely Nothing \n"
                            "Your Answer: ")
    if userAnswer != "D":
        choice = chooseLimb()
        while(choice != 1 and choice != 2 and choice != 3 and choice != 4 and choice != 5):
            choice = chooseLimb()
        checkLimb(choice, armRight, armLeft, legRight, legLeft)
        if not(checkLimb):
            choice = reChooseLimb()
            while(choice != 1 and choice != 2 and choice != 3 and choice != 4 and choice != 5):
                chooseLimb()
        loseLimb(choice, armRight, armLeft, legRight, legLeft, head)
        angerRate+=1
    else:
        correctAns+=1
        print
        
    ################### QUESTION 11 ######################
    userAnswer = raw_input("What is the maximum number of lines of code Python can handle in a single file? \n"
                           "A. INT_MAX \n"
                           "B. 10,000 \n"
                           "C. 100,000 \n"
                           "D. Unlimited \n"
                           "Your Answer: ")
    if userAnswer != "D":
        choice = chooseLimb()
        while(choice != 1 and choice != 2 and choice != 3 and choice != 4 and choice != 5):
            choice = chooseLimb()
        checkLimb(choice, armRight, armLeft, legRight, legLeft)
        if not(checkLimb):
            choice = reChooseLimb()
            while(choice != 1 and choice != 2 and choice != 3 and choice != 4 and choice != 5):
                chooseLimb()
        loseLimb(choice, armRight, armLeft, legRight, legLeft, head)
        angerRate+=1
    else:
        correctAns+=1
        print
        
    ################### QUESTION 12 ######################
    userAnswer = raw_input("What type of loop will execute at least once? \n"
                           "A. For Loop \n"
                           "B. While Loop \n"
                           "C. Do While Loop \n"
                           "D. No loops will do this \n"
                           "Your Answer: ")
    if userAnswer != "C":
        choice = chooseLimb()
        while(choice != 1 and choice != 2 and choice != 3 and choice != 4 and choice != 5):
            choice = chooseLimb()
        checkLimb(choice, armRight, armLeft, legRight, legLeft)
        if not(checkLimb):
            choice = reChooseLimb()
            while(choice != 1 and choice != 2 and choice != 3 and choice != 4 and choice != 5):
                chooseLimb()
        loseLimb(choice, armRight, armLeft, legRight, legLeft, head)
        angerRate+=1
    else:
        correctAns+=1
        print
        
    ################### QUESTION 13 ######################
    userAnswer = raw_input("A(n) ________ is passed into a function \n"
                           "A. Arguement \n"
                           "B. Actual Parameter \n"
                           "C. Formal Parameter \n"
                           "D. A and C \n"
                           "E. A and B \n"
                           "Your Answer: ")
    if userAnswer != "E":
        choice = chooseLimb()
        while(choice != 1 and choice != 2 and choice != 3 and choice != 4 and choice != 5):
            choice = chooseLimb()
        checkLimb(choice, armRight, armLeft, legRight, legLeft)
        if not(checkLimb):
            choice = reChooseLimb()
            while(choice != 1 and choice != 2 and choice != 3 and choice != 4 and choice != 5):
                chooseLimb()
        loseLimb(choice, armRight, armLeft, legRight, legLeft, head)
        angerRate+=1
    else:
        correctAns+=1
        print
        
    ################### QUESTION 14 ######################
    userAnswer = raw_input("Display \"This line will display on the screen.\" is an example of: \n"
                           "A. C++ \n"
                           "B. PHP \n"
                           "C. Python \n"
                           "D. Pseudo Code \n"
                           "Your Answer: ")
    if userAnswer != "D":
        choice = chooseLimb()
        while(choice != 1 and choice != 2 and choice != 3 and choice != 4 and choice != 5):
            choice = chooseLimb()
        checkLimb(choice, armRight, armLeft, legRight, legLeft)
        if not(checkLimb):
            choice = reChooseLimb()
            while(choice != 1 and choice != 2 and choice != 3 and choice != 4 and choice != 5):
                chooseLimb()
        loseLimb(choice, armRight, armLeft, legRight, legLeft, head)
        angerRate+=1
    else:
        correctAns+=1
        print
        
    print "You have answered ",correctAns,"out of 14 questions correctly."

###################################################################################
############################### ANSWERS FUNCTION ##################################
    
def answers(realAnswer, userAnswer):
    if userAnswer != realAnswer :
        print "The real answer was ",realAnswer
        print
    else:
        print
        
###################################################################################
############################### ROBOT FUNCTIONS ###################################
def chooseLimb():
    print
    print "________________________________________"
    print "Uh Oh!  You have angered the BattleBot!"
    print "You are ordered to choose what body part Mr. Taylor is to have destroyed:"
    choice = input("1. Right Arm \n"
                   "2. Left Arm \n"
                   "3. Right Leg \n"
                   "4. Left Leg \n"
                   "5. Head \n"
                   "The choice is yours: ")
    print "_______________________________________"
    print
    return choice

def reChooseLimb():
    print
    print "<BattleBot> You fool!  I have already removed this limb!"
    print               "CHOOSE ANOTHER LIMB OR DIE!"
    print
    choice = input("1. Right Arm \n"
                   "2. Left Arm \n"
                   "3. Right Leg \n"
                   "4. Left Leg \n"
                   "5. Head \n"
                   "The choice is yours: ")
    print "_______________________________________"
    print
    return choice

def checkLimb(choice, armRight, armLeft, legRight, legLeft):
    if choice == 1 and armRight == True:
        return False
    if choice == 2 and armLeft == True:
        return False
    if choice == 3 and legRight == True:
        return False
    if choice == 4 and legLeft == True:
        return False

def loseLimb(choice, armRight, armLeft, legRight, legLeft, head):
    if choice == 1:
        print "The BattleBot destroys Mr. Taylor\'s right arm!"
        print "Mr. Taylor screams in pain and doesn't like you anymore."
        print
        armRight = True
        return armRight
    elif choice == 2:
        print "The BattleBot destroys Mr. Taylor\'s left arm!"
        print "Mr. Taylor screams in pain and throws his newly removed arm at you, knocking you out momentarily."
        armLeft = True
        print
        return armLeft
    elif choice == 3:
        print "The BattleBot destroys Mr. Taylor\'s right leg!"
        print "Mr. Taylor screams in pain and hobbles away from the BattleBot to avoid more dismemberment."
        print
        legRight = True
        return legRight
    elif choice == 4:
        print "The BattleBot destroys Mr. Taylor\'s left leg!"
        print "Mr. Taylor hurls his Programming Logic & Design book at you."
        print
        legLeft = True
        return legLeft
    elif choice == 5:
        print "Mr. Taylor cries a little before his head is destroyed."
        print "You lose, and all of humanity is melted and recycled into fluffy kittens."
        print "Game Over."
        close()
    else:
        print "Invalid Selection."
        print "Pushing the wrong button won't save Mr. Taylor for long!"
        print

main()

No offense, but gross code you have there. You have an unbelievable amount that's just copy-pasted. I mean, all the questions are running pretty much the exact same code except for the Q it prints and the answer that's correct. This is what a function would be VERY useful for. Set it up so that you have a function that performs the question code, and just have it accept a string as the question, and a string of the correct letter. Roughly laid out as so:

# obviously this isn't valid Python code, just a template
def doQuestion(question, answer):
    print question
    get input
    if input is answer:
        do correct stuff
    else
        wrong stuff

# just make calls to that ONE segment of code with different arguments:
doQuestion('How old is the Internet?\nA. 5 years ...ETC', 'A')

Also, if I typed 'c' (lowercase) as an answer for a question whose answer is C, your program will tell me I'm wrong. It's comparing the user answer to only the uppcase letter. Just convert the user's answer to uppercase first by calling the upper() method on the string: if userAnswer.upper() == 'A' .

The problem is in
loseLimb(choice, armRight, armLeft, legRight, legLeft, head)
You return one of the booleans but don't catch any returns at the calling statement.

loseLimb(choice, armRight, armLeft, legRight, legLeft, head)
#
def loseLimb(choice, armRight, armLeft, legRight, legLeft, head):
    if choice == 1:
        print "The BattleBot destroys Mr. Taylor\'s right arm!"
        print "Mr. Taylor screams in pain and doesn't like you anymore."
        print
        armRight = True

        ## return is here  *******************************
        return armRight
#---------------------------------------------------------------------
# The problem is that you have no idea which variable is being 
# returned.  You want to pass and return a list or a dictionary instead.
#----------------------------------------------------------------------
# with a dictionary
limbs_dic = {}
limbs_dic['armRight'] = False
limbs_dic['armLeft'] = False
limbs_dic['legRight'] = False
limbs_dic['legLeft'] = False
limbs_dic['head'] = False
#
#---  pass the dictionary and keep the returned dictionary
limbs_dic = loseLimb(choice, limbs_dic)
print "limbs_dic =", limbs_dic  ## test that the changes were made
#
def loseLimb(choice, limbs_dic):
    if choice == 1:
        print "The BattleBot destroys Mr. Taylor\'s right arm!"
        print "Mr. Taylor screams in pain and doesn't like you anymore."
        print
        limbs_dic['armRight'] = True

        return limbs_dic

You can also change chooseLimb() so that it only returns a correct answer and do away with the
while(choice != 1 and choice != 2 and choice != 3 and choice != 4 and choice != 5):
but I don't have any more time until tonight. Start with Shadwickman's suggestion and have one funtion do all the work, which will get the code down to a more manageable size, which will result in more replies.

What is the obsession with global variables? Seriously.

Pass the necessary elements to your function, and return them back. You seem to be doing half of this, but you are not putting your return variables into anything.

as in:

checkLimb(armRight) #bad, your return value isn't put into anything.

This is like asking a question and not waiting around for the answer.

how about:

armRight = checkLimb(armRight) #good, armRight is now whatever was returned by checkLimb()

or even better, make a class, so you could say:

armRight.hack() #you pass the class instance.  (you would have to create the class, see below)

grrrr....global variables make zac angry.

using functions like chapter marks make zac angry too.

There is no need for a main() function. Who's your teacher? We should chat.

Here's a "Limb" class (because making bodyparts into code is fun):

class Limb:
    def __init__(self,name):
        self.name = name
        self.health = 100
        self.attached = True
    def hack(self):
        if self.attached == True:
            self.attached == False
            self.health = 0
        else:
            print "%s has already been hacked off!" %(self.name)
    def __str__(self):
        var = (self.name,self.health,self.attached)
        s = "%s, Attached: %s, Health: %d" %var
        return s

>>> armRight = Limb("Right Arm")
>>> sucess = armRight.hack()
>>> print sucess
1
>>> sucess = armRight.hack()
Right Arm has already been hacked off!
>>> print sucess
0

awesome thank you woooee the dictionary example works beautifully :)

Here is an example that checks for a correct choice based on the contents of the choice dictionary, and only prints body parts that have not already been chosen. Generally, a dictionary is used in Python to create a menu because you can define everything in one place, and only have to change the dictionary if you want to add or subtract options. I have not tested this much so it is up to you. Also. you should decide what happens when someone runs out of choices/body parts. In this example it would be
limbs_dic["game_over"] = True
You would have to have a while() loop or
if limbs_dic["game_over"] == False:
before each question.

def answers( correct_answer, choice, limbs_dic ):
    if choice.upper() != correct_answer:
        print "The real answer was ", correct_answer
        print
        limbs_dic = chooseLimb(limbs_dic)
        limbs_dic["angerRate"] += 1
    else:
        limbs_dic["correctAns"] += 1
        print "Correct"
    return limbs_dic

def ask_questions(limbs_dic):
    ######################## DISPLAY INTRO #########################
    print "                        Mr. Taylor vs The BattleBot! v1.0"
    print
    print "In order to prove yourself worth sparing to the universe, you must answer the following questions correctly."
    print "Failure to do so will result in the teacher losing a limb by the battle bot!"
    print "Your teacher's hard work is at stake!"
    print
    print "Each incorrect answer will raise the BattleBot's hatred towards you, the student!"
    print "After the BattleBot loses his temper, he will stab you!"
    print
    print "<BattleBot> Good luck, earthling.  You are going to need it..."
    print

    ################### QUESTION 1 ######################
    userAnswer = raw_input("What is not a valid variable type? \n"
                           "A. integer \n"
                           "B. string \n"
                           "C. function  \n"
                           "D. double \n"
                           "Your Answer: ")
    limbs_dic = answers( "C", userAnswer, limbs_dic )

    ################### QUESTION 2 ######################
    userAnswer = raw_input("What must be called in order for a Python script to execute? \n"
                           "A. The executable file \n"
                           "B. A minimum of one variable \n"
                           "C. The main function \n"
                           "D. namespace std; \n"
                           "Your Answer: ")
    limbs_dic = answers( "C", userAnswer, limbs_dic )

   ################### QUESTION 3 ######################
    userAnswer = raw_input("What is a string variable? \n"
                           "A. A toy for the cat \n"
                           "B. A variable containing characters \n"
                           "C. A random ASCII value \n"
                           "D. B and C \n"
                           "Your Answer: ")
    limbs_dic = answers( "B", userAnswer, limbs_dic )

    ################### QUESTION 4 ######################
    userAnswer = raw_input("What is the purpose of a function? \n"
                           "A. Readability \n"
                           "B. Quicker Programming \n"
                           "C. To store arrays \n"
                           "D. A and B \n"
                           "Your Answer: ")
    limbs_dic = answers( "B", userAnswer, limbs_dic )

    ################### QUESTION 5 ######################
    userAnswer = raw_input("What is the default \'pass by\' in Python? \n"
                           "A. Value \n"
                           "B. Cost \n"
                           "C. Reference \n"
                           "D. None \n"
                           "Your Answer: ")
    limbs_dic = answers( "C", userAnswer, limbs_dic )

    ################### QUESTION 6 ######################
    userAnswer = raw_input("Who invented Python? \n"
                           "A. Fredrick Neitzsche \n"
                           "B. Guido Van Rossum \n"
                           "C. Edward Scissorhands \n"
                           "D. Marty Friedman \n"
                           "Your Answer: ")
    limbs_dic = answers( "B", userAnswer, limbs_dic )

    ################### QUESTION 7 ######################
    userAnswer = raw_input("What type of language is Python? \n"
                           "A. Low-Level \n"
                           "B. High-Level \n"
                           "C. Scripting \n"
                           "D. Award-Winning \n"
                           "Your Answer: ")
    limbs_dic = answers( "C", userAnswer, limbs_dic )

    ################### QUESTION 8 ######################
    userAnswer = raw_input("Passing a memory address through a function is knowns as: \n"
                           "A. Pass-By-Reference \n"
                           "B. Pass-By-Value \n"
                           "C. Pass-By-Cost \n"
                           "D. This cannot be done \n"
                           "Your Answer: ")
    limbs_dic = answers( "A", userAnswer, limbs_dic )

    ################### QUESTION 9 ######################
    userAnswer = raw_input("What is the best type of loop to use for counting? \n"
                           "A. Counter Loop \n"
                           "B. Do While Loop \n"
                           "C. For Loop \n"
                           "D. Bubble-Sort Method \n"
                           "Your Answer: ")
    limbs_dic = answers( "C", userAnswer, limbs_dic )

    ################### QUESTION 10 ######################
    userAnswer = raw_input("What will this code do? \n"
                           "Number = input_stream(openFile(\"Numbers.txt\"(\"Please enter a number: \")\") \n"
                            "A. Input a number from a text file \n"
                            "B. Input a number from a user \n"
                            "C. User inputs a number and is stored to a flat file \n"
                            "D. Absolutely Nothing \n"
                            "Your Answer: ")
    limbs_dic = answers( "D", userAnswer, limbs_dic )

    ################### QUESTION 11 ######################
    userAnswer = raw_input("What is the maximum number of lines of code Python can handle in a single file? \n"
                           "A. INT_MAX \n"
                           "B. 10,000 \n"
                           "C. 100,000 \n"
                           "D. Unlimited \n"
                           "Your Answer: ")
    limbs_dic = answers( "D", userAnswer, limbs_dic )

    ################### QUESTION 12 ######################
    userAnswer = raw_input("What type of loop will execute at least once? \n"
                           "A. For Loop \n"
                           "B. While Loop \n"
                           "C. Do While Loop \n"
                           "D. No loops will do this \n"
                           "Your Answer: ")
    limbs_dic = answers( "C", userAnswer, limbs_dic )

    ################### QUESTION 13 ######################
    userAnswer = raw_input("A(n) ________ is passed into a function \n"
                           "A. Arguement \n"
                           "B. Actual Parameter \n"
                           "C. Formal Parameter \n"
                           "D. A and C \n"
                           "E. A and B \n"
                           "Your Answer: ")
    limbs_dic = answers( "E", userAnswer, limbs_dic )

    ################### QUESTION 14 ######################
    userAnswer = raw_input("Display \"This line will display on the screen.\" is an example of: \n"
                           "A. C++ \n"
                           "B. PHP \n"
                           "C. Python \n"
                           "D. Pseudo Code \n"
                           "Your Answer: ")
    limbs_dic = answers( "D", userAnswer, limbs_dic )

    print "You have answered ", limbs_dic["correctAns"], "out of 14 questions correctly."

###################################################################################
############################### ROBOT FUNCTIONS ###################################
def chooseLimb(limbs_dic):
    """  only print the limbs that are left and ask the person to
         choose the next one to amputate
    """
    print
    print "_" * 70
    print "Uh Oh!  You have angered the BattleBot!"
    print "You are ordered to choose what body part Mr. Taylor is to have destroyed:"
    #
    # I'm going to use a dictionary for the options so that one can add or
    # subtract options just by changing the dictionary
    #
    # The dictionary's key is the option number in the menu, and is a string
    # because that is what raw_input returns.
    # If an entry is not in the dictionary, it is not valid,
    # so this will catch an entry < 1 or > 5, and will also reject
    # entries like "A" or "1.5"
    #
    # Finally, we can link the "armRight" portion to the limbs dictionary
    # and only print options that are "False", i.e. not yet chosen
    choice_dic={}
    choice_dic["1"] = ["armRight", "Right Arm", \
    "The BattleBot destroys Mr. Taylor's right arm.\nMr. Taylor screams in pain and doesn't like you anymore."]

    choice_dic["2"] = ["armLeft", "Left Arm", \
    "The BattleBot destroys Mr. Taylor's left arm!\nMr. Taylor screams in pain and throws his newly removed arm at you,\n knocking you out momentarily."]

    choice_dic["3"] = ["legLeft", "Left Leg", \
    "The BattleBot destroys Mr. Taylor's left leg.\nMr. Taylor hurls his Programming Logic & Design book at you."]

    choice_dic["4"] = ["legRight", "Right Leg", \
    "The BattleBot destroys Mr. Taylor's right leg!\nMr. Taylor screams in pain and hobbles away from the BattleBot to\n avoid more dismemberment."]

    choice_dic["5"] = ["head", "Head", \
    "Mr. Taylor cries a little before his head is destroyed.\nYou lose, and all of humanity is melted and recycled into\n fluffy kittens."]

    choice_made = False         ## a valid choice was not made yet
    while not choice_made:
        options_printed = 0     ## there have to be some options left
        # dictionary keys are in hash (appears random) order so we must define
        # the order to print
        for key in range(1, len(choice_dic)+1):
           this_list = choice_dic[str(key)]
           limbs_dic_key = this_list[0]
           if limbs_dic[limbs_dic_key] == False:     ## not chosen yet
              print "%s: %s" % (key, this_list[1])
              options_printed += 1

        if options_printed > 0:     ## there are some body parts left
           choice = raw_input("The choice is yours: ")
           if choice in choice_dic:
               ## check for Falseness
               this_list = choice_dic[choice]
               print "testing, limbs_dic_key is", this_list[0]
               limbs_dic_key = this_list[0]
               if limbs_dic[limbs_dic_key] == False:
                   limbs_dic[limbs_dic_key] = True
                   choice_made = True
                   print "\n", this_list[2]
               else:                          ## part already chosen
                   print choice, "is not a valid option\n"
           else:      ## if choice in choice_dic
               print choice, "is not a valid option\n"
        else:         ## if options_printed > 0
           choice_made = True     ## exit while() loop
           print "Game Over"
           limbs_dic["game_over"] = True
    print "_" * 70
    print
    return limbs_dic


##-------------------------------------------------------------------
if __name__ == "__main__":
    ######################## DECLARE VARIABLES #####################
    limbs_dic={}
    limbs_dic["armRight"] = False
    limbs_dic["armLeft"] = False
    limbs_dic["legLeft"] = False
    limbs_dic["legRight"] = False
    limbs_dic["head"] = False
    limbs_dic["correctAns"] = 0
    limbs_dic["angerRate"] = 0
    limbs_dic["game_over"] = False

    ask_questions(limbs_dic)
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.