Fundamentals 6 min read

Master Python’s Number Guessing Game: Step-by-Step Code Walkthrough

This article walks through building a classic number‑guessing game in Python, presenting two community‑sourced solutions, detailed code snippets, explanations of the while‑loop and random modules, and enhancements for input validation and interactive range feedback, helping readers deepen their programming fundamentals.

Python Crawling & Data Mining
Python Crawling & Data Mining
Python Crawling & Data Mining
Master Python’s Number Guessing Game: Step-by-Step Code Walkthrough

Preface

A follower asked how to implement a "guess the number" game in Python. The author shares two community‑provided solutions and discusses their logic.

Solution Process

Solution by 冯诚

The approach uses a while loop, the random module to generate a target number, and input() to receive user guesses.

import random
n = random.randint(1, 100)
while True:
    a = int(input('请输入数字:'))
    if a > n:
        print('猜大了')
    elif a < n:
        print('猜小了')
    else:
        print('恭喜你猜对了')
        break

This method is straightforward and works well for most cases.

Solution by 德善堂小儿推拿-瑜亮老师

This version adds range tracking to give the player feedback about the remaining interval.

# -*-coding:utf8;-*-
#qpy:console
import random
key = random.randint(1, 100)
btm = 1
top = 100
count = 1
while True:
    try:
        user = int(input("请输入数字:"))
    except:
        continue
    if user > key:
        print('猜大了')
        print(f'数字区间为{btm}-{user}')
        top = user
    elif user < key:
        print('猜小了')
        print(f'数字区间为{user}-{top}')
        btm = user
    else:
        print(f'恭喜你共使用{count}次机会,猜对正确数字{key}')
        break
    count += 1

The code informs the player of the current possible range after each guess.

Later testing revealed a minor bug where the displayed interval could be incorrect.

import random
key = random.randint(1, 100)
btm = 1
top = 100
count = 1
while True:
    try:
        user = int(input("请输入数字:"))
    except:
        continue
    if user > key:
        if top >= user:
            top = user
        print(f'错误!正确数字比{user}小,答案就在区间{btm}-{top}之中')
    elif user < key:
        if btm <= user:
            btm = user
        print(f'错误!正确数字比{user}大,答案在区间{btm}-{top}之中')
    else:
        print(f'恭喜你共使用{count}次机会,猜对正确数字{key}')
        if count > 7:
            print('请继续努力!您还需要多练习猜数。')
        elif count == 1:
            print('啥也甭说了,快去买彩票!')
        else:
            print('你真是个机灵的小可爱!')
        break
    count += 1

The updated code fixes the interval display and adds playful messages based on the number of attempts.

Conclusion

The article demonstrates how community collaboration can refine a simple Python guessing game, improving interactivity, input handling, and user feedback while reinforcing fundamental programming concepts.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

Pythoninput validationwhile-looprandom moduleNumber Guessing Game
Python Crawling & Data Mining
Written by

Python Crawling & Data Mining

Life's short, I code in Python. This channel shares Python web crawling, data mining, analysis, processing, visualization, automated testing, DevOps, big data, AI, cloud computing, machine learning tools, resources, news, technical articles, tutorial videos and learning materials. Join us!

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.