I am trying to limit the amount of tries a person has when attempting to guess the random number. I get this error code when I run the program and can't figure out what to do next.
Traceback (most recent call last):
File "C:/Python27/coding/Guess.py", line 34, in <module>
main()
File "C:/Python27/coding/Guess.py", line 24, in main
trys(userGuess)
File "C:/Python27/coding/Guess.py", line 29, in trys
trysLeft -= 1
UnboundLocalError: local variable 'trysLeft' referenced before assignment
The code:
import random
def main():
print "Guess a number between 1 and 100."
randomNumber = random.randint(1,100)
found = False
trysLeft = 5
while not found:
userGuess = input("Your guess: ")
if userGuess == randomNumber:
print "You got it!"
found = True
elif userGuess > randomNumber:
trys()
print "Guess lower!"
else:
trys()
print "Guess higher!"
def trys():
trysLeft -= 1
print "You have %d trys left." %trysLeft
if __name__ == "__main__":
main()
You have 3 options to fix this:
Put trysLeft in a global (not a good idea)
Add function trys() to your class and reference it as self.trysLeft
Pass the variable into the trys() function.
You need to pass trysLeft to the function for it to see it ...
def trys(trysLeft):
trysLeft -= 1
print "You have %d trys left." %trysLeft
return trysLeft
and then when you call trys ...
trysLeft = trys(trysLeft)
The problem is that you're assigning trysLeft in the function, so it assumes it has local (rather than global) scope. But you actually want to assign the global variable, so you need to declare that trysLeft has global scope. Change your trys() function to the following:
def trys():
global trysLeft
trysLeft -= 1
print "You have %d trys left." %trysLeft
For more information, see the FAQ
FWIW, the correct way to solve this would be to pass a variable to your function rather than use globals, but that's outside the scope of your question.
def trys(self):
self.trysLeft-=1
Should do it!
Self is referring to the instance of the class that you are currently in.
Similar to this in java and Me in vba.
Related
I am attempting to make a simple guessing game for my class with graphics and I'm trying to make an attempt counter. This is the area where my code is going wrong.
def value():
guess = int(input("Enter your guess: "))
if guess > num:
attempts = attempts + 1
turtle.clearscreen()
interface()
tooHigh()
attempt = turtle.Turtle()
attempt.speed(0)
attempt.color("white")
attempt.penup()
attempt.hideturtle()
attempt.goto(-250 , 200)
attempt.write(guess, font=("Courier", 14, "bold"))
value()
elif guess < num:
attempts = attempts + 1
turtle.clearscreen()
interface()
tooLow()
attempt = turtle.Turtle()
attempt.speed(0)
attempt.color("white")
attempt.penup()
attempt.hideturtle()
attempt.goto(-250 , 200)
attempt.write(guess, font=("Courier", 14, "bold"))
value()
elif guess == num:
attempts = attempts + 1
turtle.clearscreen()
interface()
yes()
attempt = turtle.Turtle()
attempt.speed(0)
attempt.color("pink")
attempt.penup()
attempt.hideturtle()
attempt.goto(-250 , 200)
attempt.write(guess, font=("Courier", 14, "bold", "underline"))
print ("Correct!")
else:
print ("ERROR")
def startScreen():
begin = input("Start the game?: ")
if begin == 'yes':
value()
elif begin == 'instructions':
instructions()
startScreen()
elif begin == 'no':
sys.exit()
else:
print ("Unrecognised answer.")
startScreen()
attempts = 0
num = random.randint(1,1000)
interface()
startScreen()
The error I receive is:
Traceback (most recent call last):
File "D:\Desktop\Python Programs\Game.py", line 154, in <module>
`startScreen()`
File "D:\Desktop\Python Programs\Game.py", line 141, in startScreen
`value()`
File "D:\Desktop\Python Programs\Game.py", line 110, in value
`attempts = attempts + 1`
UnboundLocalError: local variable 'attempts' referenced before assignment
It doesn't seem possible to move attempts into the function as it constantly calls itself, resetting attempts each time.
I am unsure why this is occurring so any help would be greatly appreciated. Thanks!
The reason you are getting this error is because of something called variable scope. You have defined the variable attempts outside of the function value, so the function will not recognize any local variable by the name attempts unless you explicitly put the statement global attempts at the beginning of your function. This will tell the function that you want to use the variable attempts that you defined in your main program. That should look like this:
def value():
global attempts
#function code
Alternatively, you can allow your function value to take an argument, and pass the variable attempts into that. That would look something like this:
def value(attempts):
#function code
#you can use the variable attempts as needed, since you're passing it directly into the function
#call the function however you want
attempts = 0
value(attempts)
In the function, when you access a variable for assignment, it by-default is treated as a local variable. So, to make Python know that the variable that you want to modify is a global variable, you do the following:
def value():
global attempts
# rest of your code
#Intro
import time
import random
def restart():
bowlSize = random.randint(1,100)
bowlStrawberries = 0
def lel():
while bowlSize > bowlStrawberries:
if (addCheck + bowlStrawberries) > bowlSize:
print('You´re filling the bowl..')
time.sleep(2)
print('...and...')
time.sleep(2)
print('Your mom slaps you!')
restart()
def addStrawberries():
print('The bowl has ' + str(bowlStrawberries) + ' strawberries in it')
print('How many strawberries do you want to add?')
addCheck = input()
lel()
print('STRAWBERRY (:')
time.sleep(2)
print('Okey so you have a bowl kinda')
time.sleep(2)
print('And you have a bag with 100 strawberries')
time.sleep(2)
print('So ur mom forces you to fill the bowl')
time.sleep(2)
print('But she will slap you if a strawberry drops on the floor')
time.sleep(2)
print('So you have to fill it up in as few tries as possible without overfilling it')
time.sleep(2)
restart()
addStrawberries()
I´m new to Programming, it´s my fifth day today and I can´t understand why I get errors. You propably had similar questions but I am new and I don´t know what to search. I basically want it to restart when I pick a higher value than the bowls space.
Exact errors:
Traceback (most recent call last):
File "C:/Users/***/Documents/strenter code herew.py", line 44, in <module>
addStrawberries()
File "C:/Users/***/Documents/strw.py", line 27, in addStrawberries
lel()
File "C:/Users/***/Documents/strw.py", line 14, in lel
if (addCheck + bowlStrawberries) > bowlSize:
NameError: name 'addCheck' is not defined
addCheck is a local variable in addStrawberries, meaning it can't be seen outside of the function. I recommend passing it as an argument to lel, i.e. call lel(addCheck) and define lel as def lel(addCheck). Alternatively you could make addCheck a global variable by inserting the statement global addCheck in addStrawberries before assigning it, but global variables tend to be icky.
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()
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
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.
All I needed to go was define the variable outside the function and then put:
global lives in the function.
Job done.
I'm having some issues with this code. There is a lot of other code to go with it but none that will interfere or have any affect on the issue I'm having. So basically, when I run the code and we get to the for loop at the bottom, it prints nothing because apparently the variable 'walls' = 0, even though I've already given it a valid input. If anyone could help it would be much appreciated.
global walls
global wallLengths
walls = 0
wall = 0
wallLengths = 0
def clientDetails():
#global walls
print("Welcome to the InHouse Solutions Room Painting Price Calculator")
print("STEP 1 - CLIENT DETAILS")
print("Please enter your full name")
userName = input(">>>")
print("Please enter your post code")
postCode = input(">>>")
print("Please enter you first address line here:")
addressLineOne = input(">>>")
print("Please enter your second address line here (OPTIONAL)")
addressLineTwo = input(">>>")
print("Thank you for your information")
print (userName)
print (addressLineOne + ", " + addressLineTwo + ", " + postCode)
print (" ")
def ValidationOne():
print ("Is this information correct? Pleast enter Yes or No")
clientDetailsCorrect = input(">>>")
if clientDetailsCorrect == "no" or clientDetailsCorrect == "No":
clientDetails()
elif clientDetailsCorrect == "Yes" or clientDetailsCorrect == "yes":
roomDimensions()
else:
("Invalid response, please try again")
ValidationOne()
ValidationOne()
def roomDimensions():
global walls
print ("STEP 2 - ROOM DIMENSIONS")
def ValidationTwo():
global walls
print ("How many walls does your room have?")
walls = int(input(">>>"))
if walls > 10 or walls < 3:
print("Invalid, please enter a number between 3 and 10")
ValidationTwo()
elif walls == " " or walls == "":
print("Invalid")
ValidationTwo()
def ValidationThree():
global walls
print ("How tall is the room in meters?")
roomHeight = float(input(">>>"))
if roomHeight < 2.4 or roomHeight > 6:
print ("Invalid, please enter a value between 2.4 and 6")
ValidationThree()
def IndividualWalls():
global wallLengths
global walls
for i in range(1,walls):
print("Please enter the width of wall" , i)
wallLengths[i] = float(input(">>>"))
ValidationTwo()
ValidationThree()
IndividualWalls()
clientDetails()
there is no need to use 'global' keyword when declaring a global at the top of the script:
>>> walls = 0
>>> def increase_walls():
... global walls
... walls += 1
... print walls
...
>>> increase_walls()
1
I can't comment to your question because I don't have over 50 reputation so I will ask here
Can you tell me what the function roomDimensions does?
I tried to run it and you have some deep recursion problem (you can't call recursion function without any if - it will run forever) BUT the first thing that I notice is that you don’t initialize the walls variable so it will not be global variable it will be non-local variable. and you don't call any inner function ( ValidationTwo, ValidationThree,IndividualWalls)
so you main problems are: (handle them in this order)
walls initialize
you didn't call any inner function
deep recursion
here is my example for the use of the three of above:
global_var = 12
def outer():
global global_var
print("*"*10)
print('hello im outer function')
print("*"*10)
def inner1():
global global_var
print('hello im inner1 function')
if global_var < 10:
return 'end for inner1'
print ('global_var is: ' + str(global_var))
global_var -= 1
return inner1()
def inner2():
global global_var
print('hello im inner2 function')
if global_var >= 10:
return 'end for inner1'
print ('global_var is: ' + str(global_var))
global_var += 1
return inner2()
if global_var >= 10:
return inner1()
else:
return inner2()
if __name__ == '__main__':
print outer()
I have the following code:
#AON = Amount of Numbers to average
def general():
print "Enter how many numbers you will enter."
print "Maximum amount is 10: "
aon = raw_input()
try:
aon = int(aon)
if aon >= 10:
print "I cannot average more than 10 numbers."
general()
else:
start_average()
except ValueError:
print "You entered an invalid input, try again."
general()
def start_average():
if aon == 1:
print "You cannot average one number."
general()
elif aon == 2:
def first_number():
print "First number: "
first_ni = raw_input()
second_number()
first_number()
def second_number():
print "Second number: "
second_ni = raw_input()
ans_two = first_ni / second_ni
second_number()
final_two()
elif aon == 3:
def third_number():
first_number()
second_number()
print "Third number: "
third_ni = raw_input()
ans_three = ans_two / third_ni
third_number()
final_three()
elif aon == 4:
def fourth_number():
first_number()
second_number()
third_number()
print "Fourth number: "
fourth_ni = raw_input()
ans_four = ans_three / fourth_ni
fourth_number()
final_four()
elif aon == 5:
def fifth_number():
first_number()
second_number()
third_number()
fourth_number()
print "Fifth number: "
fifth_ni = raw_input()
ans_five = ans_four / fifth_ni
fifth_number()
final_five
def final_two():
final_input = ans_two
final_answer()
def final_three():
final_input = ans_three
final_answer()
def final_four():
final_input = ans_four
final_answer
def final_five():
final_input = ans_five
final_answer()
def final_six():
final_input = ans_six
final_answer()
def final_seven():
final_input = ans_seven
final_answer()
def final_eight():
final_input = ans_eight
final_answer()
def final_nine():
final_input = ans_nine
final_answer()
def final_answer():
listofnumbers = [first_ni, second_ni, third_ni, fourth_ni, fifth_ni, sixth_ni, seventh_ni, eight_ni, ninth_ni]
print "The average of your numbers:"
print listofnumbers
print "Is = %d." % final_input
general()
It's purpose is to find the average of a number, but when I run it through PowerShell, I get the following error:
Traceback (most recent call last):
File "average.py", line 97, in <module>
general()
File "average.py", line 10, in general
general()
File "average.py", line 10, in general
general()
File "average.py", line 12, in general
start_average()
UnboundLocalError: local variable 'start_average' referenced before assignment
I've probably done this more throughout my code, and I just made this, but I just don't know how to fix it or what is the error showing! I don't understand.
It's hard to tell from what you've pasted, because you've clearly broken the indentation.
But it looks like this code:
print "Enter how many numbers you will enter."
print "Maximum amount is 10: "
… is meant to be inside general, while this code:
aon = raw_input()
try:
aon = int(aon)
if aon >= 10:
print "I cannot average more than 10 numbers."
general()
else:
start_average()
except ValueError:
print "You entered an invalid input, try again."
general()
… is meant to be at module level.
Code is executed in the order it appears. Function definitions are just code, like anything else. So, you can't call a function before you define it, because the function doesn't exist yet.
You're probably about to object, with an example like this:
def foo():
bar()
def bar():
print('Hi!')
foo()
It looks like we're calling bar before it exists, and yet it works. How?
Well, the definition of foo is being executed before bar exists, but that's fine. That just defines a function that will, when run, call whatever bar means. As long as we've defined bar before we call it—and we have—everything is fine.
However, you have a number of similar problems in your code. For example, let's look at this part:
elif aon == 2:
def first_number():
print "First number: "
first_ni = raw_input()
second_number()
first_number()
def second_number():
print "Second number: "
second_ni = raw_input()
ans_two = first_ni / second_ni
second_number()
final_two()
That first_ni is a local variable within the first_number function. Every time you call first_number, a new first_ni gets defined, but only visible within that function. You can't use it in second_number, because second_number can only see its own local variables, and global variables, and first_ni is neither.
The concept you need to understand is called scope. Python has some nice tools to help you understand scope. You can print out locals() and globals() and dir() at any part of your program to see what's in scope there. But you'll need to read the tutorial first.
Indentation and a few other things are questionable. I'm not sure why you're defining all of these functions inside of other functions... I think this will do what you want. You're going to need a lot more error checking though (making sure the inputs are integers, divide by 0, etc.)
>>> def getMean(maxNumsToDivide):
... listNums = []
... for i in range(maxNumsToDivide):
... num = raw_input("Please enter a number: ")
... if not num:
... break
... listNums.append(int(num))
... return float(sum(listNums))/len(listNums)
...
>>> getMean(100)
Please enter a number: 2
Please enter a number: 3
Please enter a number: 4
Please enter a number: 5
Please enter a number: 3
Please enter a number:
3.4