Reputation: 3
I'm trying to solve the "Guessing Game" problem in the Harvard CS50P course (problem set 4). The assignment is to prompt the user for a number x , generate a random number y in the range 1-x, and then have the user guess y, exiting the program when the guess is correct. Any input that's not a number should reprompt the user. It works just fine in the console, but I get the "timed out while waiting for program to exit" error when I check the code with check50. I assume the problem is caused by the while loop in the main() function and tried rephrasing it multiple ways, but I still couldn't fix it. I copied my code below, any help or tip is appreciated!
check50 output:
:) game.py exists
:) game.py rejects non-numeric level
:) game.py rejects out-of-range level
:) game.py accepts valid level
:) game.py rejects non-numeric guess
:) game.py rejects out-of-range guess
:) game.py outputs "Too large!" when guess is too large
:( game.py outputs "Just right!" when guess is correct
timed out while waiting for program to exit
:) game.py outputs "Too small!" when guess is too small
from random import choice
def main():
number = choice((list(range(1, get_level() + 1)))) # get random number y from range 1-x
while True: # have user guess y
try:
guess = int(input("Guess: "))
if guess > 0:
if guess < number:
print("Too small!")
elif guess > number:
print("Too large!")
elif guess == number:
print("Just right!")
break # break out of loop if guess is correct
except ValueError:
pass
def get_level():
while True:
try:
level = int(input("Level: "))
if level > 0:
return level
except ValueError:
pass
main()
Upvotes: 0
Views: 4236
Reputation: 36
import sys
then use
sys.exit("Just Right!")
instead of
print("Just Right!")
break
Upvotes: 2