Write a program that generates a random number and asks the user to guess what the number is. If the user's guess is higher than the random number, the program should display "Too high, try again." If the user's guess is lower than the random number, the program should display "Too low, try again." The program should use a loop that repeats until the user correctly guesses the random number.

Engineering · College · Sun Jan 24 2021

Answered on

Here is a Python program that achieves this behavior using the `random` module for generating random numbers and a loop to keep asking the user for a guess until they get it right:

```python import random

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

# Initialize a variable to keep track of the user's guess. # Initially, it is set to None, meaning the user hasn't guessed yet. user_guess = None

# Loop until the user guesses the random number while user_guess != random_number: # Ask the user for their guess user_guess = int(input("Guess the number (between 1 and 100): ")) # Check if the guess is too high, too low, or just right if user_guess > random_number: print("Too high, try again.") elif user_guess < random_number: print("Too low, try again.")

# Congratulate the user for guessing the number correctly print("Congratulations! You've guessed the number correctly!") ```

This program will keep running until the user guesses the correct number. Note that `input()` is used to read the user's guess and `int()` is used to convert it to an integer for comparison with the random number.

Extra: A couple of concepts in this program are fundamental to understanding how it works.

1. `random.randint(start, end)`: This is a function from Python's `random` module that generates a random integer in the range from `start` to `end`, inclusively.

2. Loop (`while` loop): The `while` statement allows you to repeat a block of code as long as a condition is true. In this case, it repeats asking the user for their guess until their guess is equal to the random number.

3. Conditional Statements (`if`, `elif`, `else`): These structures allow the program to execute different blocks of code based on certain conditions—in this case, whether the user's guess is higher than, lower than, or equal to the random number.

4. Type Conversion: The `input()` function always returns a string, so it's necessary to convert the user's input to an integer using `int()` before comparing it to the random number.

5. User Input: `input()` is used to get input from the user via the command line. This is the way we allow the user to guess the number.

6. Comparison Operators: In the conditions for the `if` statements, we use comparison operators (`>`, `<`, `!=`) to compare the user's guess to the randomly generated number.

Related Questions