[英]Python guessing game code keeps crashing after 1 guess. How would i fix this?
My code keeps crashing after I put in the 1st guess I make.在我输入第一个猜测后,我的代码不断崩溃。 I've looked at syntax and dont think that's a problem how do I make it so it goes past the 1st guess and executes it.我看过语法,不认为这是一个问题,我如何使它超过第一个猜测并执行它。 When I put the guess in it just puts in all the prompts at once, and how do I call the function properly at the end?当我输入猜测时,它只是一次性输入所有提示,最后如何正确调用该函数? Any help would be appreciated.任何帮助,将不胜感激。
Import time,os,random
def get_int(message):
while True:
user_input = input(message)
try:
user_input = int(user_input)
print('Thats an integer!')
break
except:
print('That does not work we need an integer!')
return user_input
def game_loop():
fin = False
while not fin:
a = get_int('give me a lower bound:')
b = get_int('give me a upper bound:')
if a < 0:
print("that doesn't work")
if a > b:
a, b = b, a
print(a,b)
os.system('clear')
print("The number you guess has to be between " + str(a) + "and " + str(b) + '.')
num_guesses = 0
target = random.randint(a,b)
time_in = time.time()
while True:
print('You have guessed ' + str(num_guesses) + " times.")
print()
guess_input = get_int('guess a number')
if guess_input == target:
print("Congrats! You guessed the number!")
time_uin = time.time()
break
elif guess_input < a or guess_input > b:
print("guess was out of range... + 1 guess")
elif guess_input < target:
print("Your guess was too low")
else:
print("Your guess was to high")
num_guesses = num_guesses + 1
if num_guesses<3:
print('Einstein?')
else:
print('you should be sorry')
time_t = time_uin - time_in
print('it took' + str(time_t) + 'seconds for you to guess a number')
print()
time_average = time_t / (num_guesses+1)
print('It took an average of' + str(time_average)+"seconds per question")
print()
while True:
play_again = input ('Type y to play again or n to stop')
print()
if play_again == 'n':
fin = True
print('Thank God')
time.sleep(2)
os.system('clear')
break
elif play_again == 'y':
print('here we go again')
time.sleep(2)
os.system('clear')
break
else:
print('WRONG CHOCICE')
break
game_loop()
If guess_input
!= target
on the first iteration of the loop, time_uin
is referenced before assignment.如果guess_input
!= target
在循环的第一次迭代中,则在赋值之前引用time_uin
。 Hence the error:因此错误:
UnboundLocalError: local variable 'time_uin' referenced before assignment
Solution is to run the following only if guess_input
== target
.解决方案是仅当guess_input
== target
时才运行以下guess_input
。
if num_guesses<3:
print('Einstein?')
else:
print('you should be sorry')
time_t = time_uin - time_in
print('it took' + str(time_t) + 'seconds for you to guess a number')
print()
time_average = time_t / (num_guesses+1)
print('It took an average of' + str(time_average)+"seconds per question")
print()
Please follow coppereyecat's link to learn how to debug a basic Python program.请按照coppereyecat 的链接学习如何调试基本的Python 程序。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.