Game: Guess the Correct Number.

 

Learn with Hafiza Palwasha




How to design a game 'To Guess a Number' ?

Lecture No. 1

1. Open Python IDLE and open a new file as shown below:


2. Now the new file will open like this:


3. Now you have to write the following code for the game 'To Guess A Number':

import random

def main():
    print("Welcome to the Guess the Number game!")
    secret_number = random.randint(1, 20)
    attempts = 0

    while True:
        try:
            guess = int(input("Guess a number between 1 and 20: "))
            attempts += 1

            if guess < secret_number:
                print("Too low! Try again.")
            elif guess > secret_number:
                print("Too high! Try again.")
            else:
                print(f"Congratulations! You guessed the number {secret_number} in {attempts} attempts.")
                break
        except ValueError:
            print("Invalid input. Please enter a valid number.")

if __name__ == "__main__":
    main()

4. This written code will appear on screen as shown below:


5. Now click on 'run' and then click on 'Run Module' as shown below:


6. The code will run as shown below:




7. Now enter any number  between this range and press enter, it will show either the number is correct, too high or too low as shown below:

 

8. As it is saying that, the number is too high, so we have to guess some less number than 8 as I did the next try:


9. So luckily, I guessed the correct number and I won the game.

Homework Task

Now you have to change the range of number as shown below in the above code to show your skills:
1. 1 to 50.
2. -50 to 50.
3. -20.25 to 20.25

Enter your comments if you are facing some difficulty.

Comments