Skip to content

Instantly share code, notes, and snippets.

@davidmerwin
Last active November 22, 2023 04:33
Show Gist options
  • Save davidmerwin/8f7d6f6140440181a5ecd7b1f1654260 to your computer and use it in GitHub Desktop.
Save davidmerwin/8f7d6f6140440181a5ecd7b1f1654260 to your computer and use it in GitHub Desktop.
This code tries to guess a number between 1 and 10, then prints an error message if it is wrong.

Number Guessing Game

Preview:
import random

number = random.randint(1, 10)

while True:
    guess = int(input('Guess a number between 1 and 10: '))

    if guess < 1 or guess > 10:
        print('Invalid input. Please enter a number between 1 and 10.')
    elif guess == number:
        print('Congratulations! You guessed the correct number.')
        break
    else:
        print('Wrong guess. Try again.')

# Notes:
# There is no need to optimize this code snippet further as it is already performant for its purpose.
Associated Context
Type Code Snippet ( .py )
Associated Tags Random number generation Input validation Conditional statements Integer data type Break statement Comparison operator Error handling Data extraction User input validation Number guessing game Integer conversion Looping Range of numbers User feedback
💡 Smart Description This code tries to guess a number between 1 and 10, then prints an error message if it is wrong.
This code generates a random number between 1 and 10, then prompts the user to guess the number. It provides feedback on whether the guess is correct or not, and continues until the correct number is guessed.
🔎 Suggested Searches random number generator
How to generate random numbers using Python
program to find a choice of 1 and 10 in an integer generation
Code for calculating the correct guess from input string
function to determine how to use Random int
Python random number guessing game
Python code to generate random number and ask for user input
Python code to validate user input for a number between 1 and 10
Python code to implement a number guessing game with while loop
Python code to break out of a while loop when user guesses the correct number
Related Links https://www.w3schools.com/python/ref_random_randint.asp
https://www.w3schools.com/python/
https://www.w3schools.com/python/default.asp
https://www.pythonforbeginners.com/random/how-to-use-the-random-module-in-python
https://realpython.com/how-to-use-numpy-arange/
https://www.pythoncentral.io/how-to-slice-listsarrays-and-tuples-in-python/
https://docs.python.org/3/library/random.html
https://www.askpython.com/python-modules/python-random-module-generate-random-numbers-sequences
https://realpython.com/python-random/
Related People Jack Cheng, David Merwin
Sensitive Information No Sensitive Information Detected
Shareable Link https://davidmerwin.pieces.cloud/?p=d43e4a8449
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment