DEV Community

Cover image for Learn to Code: Create a Random Number Guessing Game in Python
Azeem Akhtar
Azeem Akhtar

Posted on • Updated on

Learn to Code: Create a Random Number Guessing Game in Python

In this article, we will walk through the process of creating a simple program that generates a random number and asks the user to guess it. This can be a fun and interactive way to learn about programming and practice your coding skills. We will be using a programming language of your choice, but for the sake of simplicity, we will provide examples in Python.

Generating a Random Number

The first step is to generate a random number that the user will have to guess. In Python, we can make use of the random module to accomplish this. Here's an example code snippet:

import random

def generate_random_number():
    return random.randint(1, 100)
Enter fullscreen mode Exit fullscreen mode

The random.randint(a, b) function generates a random integer between a and b, inclusive. In this case, we are generating a random number between 1 and 100. Feel free to adjust the range according to your preferences.

Asking the User for Guesses

Now that we have a random number, we can start asking the user to guess it. We will prompt the user for input and compare their guess with the randomly generated number. Here's an example code snippet to get you started:

def ask_user_for_guess():
    guess = int(input("Take a guess: "))
    return guess

def check_guess(random_number, user_guess):
    if user_guess < random_number:
        print("Too low!")
    elif user_guess > random_number:
        print("Too high!")
    else:
        print("Congratulations! You guessed it!")

# Main program
random_number = generate_random_number()

while True:
    user_guess = ask_user_for_guess()
    check_guess(random_number, user_guess)
    if user_guess == random_number:
        break
Enter fullscreen mode Exit fullscreen mode

In this code, we define two functions: ask_user_for_guess() and check_guess(random_number, user_guess). The ask_user_for_guess() function prompts the user to enter their guess and returns it as an integer. The check_guess() function compares the user's guess with the randomly generated number and provides feedback accordingly.

We then use a while loop to continuously ask the user for guesses until they guess the correct number. Once the user guesses the correct number, the loop breaks, and the program ends.

Conclusion

Congratulations! You have successfully written a program that generates a random number and asks the user to guess it. This exercise is a great way to practice your coding skills and understand the basics of user input and random number generation in programming.

Feel free to modify the code and add additional features to make the game more interesting. You could keep track of the number of guesses the user takes, provide hints, or even create a high-score system.

Remember to have fun and keep exploring my profile!

Top comments (0)