Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python

How to continue loop after exception?

import random
GREETING = "======> Welcome to Rando <====="

def start_game():

    print(GREETING.upper())
    answer = random.randint(1,10)
    num_of_guess = 1
    print(answer)

    rules = print("Select an integer between 1 & 10, and I will tell you if it's too high or too low. \n If you can\'t correctly guess my number within 3 tries, it\'s GAMEOVER!")

    try:
        while num_of_guess < 4:
            guess = int(input("Pick an integer between 1 & 10:  "))
            if 1 < guess > 10:
                raise ValueError
                #continue
            if guess == answer:
                print("Congrats! You guessed my number")

            else:
                if guess > answer:
                    print('Too High')
                else:
                    print("Too Low")

            num_of_guess += 1


    except ValueError as err:
        print(("Number has to be integer between 1 & 10, try again!"))




start_game()   

Having some issues with my code. Once it raises the ValueError, the program stops. Where I have the "#continue" located is where I thought I had to put the continue for it to run, but that didn't work either.

1 Answer

boi
boi
14,242 Points

Put your try/except inside the while loop.

import random
GREETING = "======> Welcome to Rando <====="

def start_game():

    print(GREETING.upper())
    answer = random.randint(1,10)
    num_of_guess = 1
    print(answer)

    rules = print("Select an integer between 1 & 10, and I will tell you if it's too high or too low. \n If you can\'t correctly guess my number within 3 tries, it\'s GAMEOVER!")


    while num_of_guess < 4:
      try:

        guess = int(input("Pick an integer between 1 & 10:  "))
        if guess < 1 or guess > 10:
            raise ValueError
            #continue
        if guess == answer:
            print("Congrats! You guessed my number")

        else:
            if guess > answer:
                print('Too High')
            else:
                print("Too Low")

        num_of_guess += 1


      except ValueError as err:
          print(("Number has to be integer between 1 & 10, try again!"))




start_game()   

Thanks for helping out with this one. I figured it out finally after many many iterations.