Python & OpenAI beginner journey 4 | while: ‘continue'

Python & OpenAI beginner journey 4 | while: ‘continue'

As a junior programmer I still find it hard to open up my main OpenAI Chatbot program in the morning and get an overview of where I was.

To make this easier and also improve my coding skills in general I am now adding a small python exercise to my daily morning routine.

For now I am just getting these exercises from ChatGPT, but I’ll look for other sources as well.

Today I just built a small number guessing game. I did this before but the one new thing I learned is the ‘continue’ statement, which allows me to restart the ‘while’ loop. Very useful.

Anything else you think my code is missing? 🙂

import random
import sys

def main():
    # Generate a random number between 1 and 100
    target_number = random.randint(1, 100)

    # Initialize the number of attempts
    attempts = 0

    # Initialize the guess number
    user_guess = 0

    print("Welcome to the Guess the Number Game!")

    # Guessing loop
    try:
        while target_number != user_guess:
            attempts += 1
            try:
                user_guess = int(input(f'Guess {attempts}: '))
            except ValueError:
                print('please enter a number')
                continue  # Skip the rest of the loop iteration and ask for a new guess
            if user_guess > target_number:
                print('too high')
            elif user_guess < target_number:
                print('too low')
            elif user_guess == target_number:
                print('just right')
            else:
                print('Error')
    except KeyboardInterrupt:
        sys.exit('Exit')

    print(f'You found {target_number} after {attempts} attempts')

if __name__ == '__main__':
    main()