In this number-guessing game in Python, the user must guess a randomly generated number between 1 and 6. The game will give hints like Too low or Too high for the user hint. The code will repeat until the user guesses correctly.
Number guess code example in Python.
import random
print("\n\n-------Welcome to the Number Guessing Game-------")
x = random.randint(1, 6)
attempts = 0
while True:
n = int(input("Enter your guess between 1 To 6: "))
attempts += 1
if n < 1 or x > 6:
print("Please enter a number between 1 and 100.")
continue
if n < x:
print("Too low! Try again.")
elif n > x:
print("Too high! Try again.")
else:
print("Congratulations! You guessed it in",attempts,"tries.")
break
Written by Shubhranshu Shekhar, who has trained 20000+ students in coding.
Shubhranshu Shekhar is a coding instructor, mentor, and founder of VSIT Delhi with 20+ years of teaching experience (since 2004). He has guided many students who are now working in multinational companies and specializes in Full Stack Development, Python, Digital Marketing, and Data Analytics.