होम › Code Lab (Hindi) › Python में Guess the Number गेम
Python में Guess the Number गेम — कोड, लॉजिक और खेल
ब्राउज़र में Python का Guess the Number गेम चलाएँ, कोड कॉपी या डाउनलोड करें, और लॉजिक को समझें। · स्तर: Beginner · Read this in English
Python कोड चलाएँ
आउटपुट
लॉजिक कैसे काम करता है (मुफ़्त)
- random.randint(1, 100) एक secret number चुनता है। गेम इसे पहले से नहीं जानता, इसलिए हर राउंड अलग होता है।
- attempts = 0 गिनता है कि खिलाड़ी ने कितने guesses किए।
- while True: तब तक guessing दोहराता है जब तक खिलाड़ी जीत न जाए। loop सिर्फ break से खत्म होता है।
- input() खिलाड़ी के type करने का इंतज़ार करता है। int() से पहले isdigit() से जाँच होती है, ताकि अक्षर डालने पर गेम crash न हो।
- if / elif / else guess को secret से compare करता है: कम, ज़्यादा, या सही।
- सही guess के बाद break loop से बाहर निकलता है, और f-string attempts की संख्या दिखाती है।
इसमें आप ये concepts सीखेंगे
- random module
- break के साथ while loop
- input() और type checking
- if / elif / else
- f-strings
पूरा कोड (plain text)
import random
def play_guess_the_number():
secret = random.randint(1, 100)
attempts = 0
print("I have picked a number between 1 and 100.")
while True:
guess_text = input("Your guess: ")
if not guess_text.isdigit():
print("Please type a whole number.")
continue
guess = int(guess_text)
attempts += 1
if guess < secret:
print("Too low! Try a bigger number.")
elif guess > secret:
print("Too high! Try a smaller number.")
else:
print(f"Correct! You won in {attempts} attempt(s).")
break
play_guess_the_number()
PyDebug पर अभ्यास करें
खेलने के बाद इन मुफ़्त exercises से इस idea को debugging की आदत बनाएँ: