Reputation: 49
How do you minus one from an INT in a function?
This is what I'm trying:
try:
lives
except NameError:
lives = 6
else:
lives = lives-1
print("\nWrong!\nYou have " +str(lives)+ " lives remaining\n")
But it doesn't work.
The lives are always at 6 :(
Any ideas?
UPDATE:
def main():
used = []
print(blanks)
choice = input("\nEnter a letter:")
lives -= 1
print("\nWrong!\nYou have " +str(lives)+ " lives remaining\n")
used.append(choice)
main()
Upvotes: 1
Views: 25799
Reputation: 49
All I needed to go was define the variable outside the function and then put:
global lives
in the function.
Job done.
Upvotes: 0
Reputation: 2424
If lives wasn't defined before, than try: lives
will always get you to the except section.
if you define lives before this code (by assigning it something) or inside the try section, you'll get to see the -1 in action.
try:
lives = 1
except NameError:
lives = 6
else:
lives = lives-1
print lives
will output 0
as well as:
lives = 1
try:
lives
except NameError:
lives = 6
else:
lives = lives-1
print lives
EDIT:
For your comment, here is some sample code that does something like what you are probably trying to achieve, that is a game of guess the letter. Hopefully this will help you.
def main():
# The setup
right_answer = "a"
lives = 6
# The game
while lives > 0:
choice = raw_input("Enter a letter:")
if choice == right_answer:
print "yay, you win!"
break
else:
lives -= 1
print "nay, try again, you have", lives, "lives left"
else:
print "you lose"
# This will call our function and run the game
if __name__ == "__main__":
main()
** written fro python 2.7, for python 3 the prints will need parentheses.
Upvotes: 0
Reputation: 2620
The real reason you are seeing 6 is because the NameError is thrown, and therefore your else clause is never actually executed
NameError: name 'lives' is not defined
Upvotes: 2