How to Create a Practise Program for Python?

Estimated read time 2 min read

Here’s an example program that you can use for practice in Python. This program generates a random number between 1 and 100, and asks the user to guess the number. The program gives hints to the user whether their guess is too high or too low, until they guess the correct number.

import random

# generate a random number between 1 and 100
number = random.randint(1, 100)

# ask the user to guess the number
while True:
    guess = input("Guess a number between 1 and 100: ")
    try:
        guess = int(guess)
    except ValueError:
        print("Invalid input. Please enter a number.")
        continue
    if guess < 1 or guess > 100:
        print("Number must be between 1 and 100.")
        continue
    if guess < number:
        print("Too low. Try again.")
    elif guess > number:
        print("Too high. Try again.")
    else:
        print("Congratulations! You guessed the number.")
        break

In this example, we use the random module to generate a random integer between 1 and 100. We then use a while loop to repeatedly ask the user to guess the number, until they guess correctly.

Inside the loop, we use the input() function to get the user’s guess as a string. We convert the string to an integer using the int() function, and handle any exceptions that may occur if the input is not a valid number.

We check whether the guess is within the range of 1 to 100 using an if statement. If the guess is too low or too high, we print a message to the user to give them a hint, and continue the loop. If the guess is correct, we print a congratulatory message and break out of the loop.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply