Python Number Guessing Game: Code Tutorial

Here is a simple Python code for a guessing number game:

import random

# 生成一个1到100之间的随机数
number = random.randint(1, 100)

print("欢迎来到猜数字游戏!")
print("我已经生成了一个1到100之间的随机数,你需要猜出这个数是多少。")

guess = None
count = 0

while guess != number:
    guess = int(input("请猜一个1到100之间的数字:"))
    count += 1

    if guess < number:
        print("猜小了,再试试大一点的数字。")
    elif guess > number:
        print("猜大了,再试试小一点的数字。")
    else:
        print(f"恭喜你,猜对了!你用了{count}次猜出了这个数字。")

print("游戏结束,谢谢参与!")

By running this code, you can play a number guessing game with the computer. You need to input a number between 1 and 100 until you guess correctly. The game will tell you if your guess is too high or too low, until you guess correctly. Finally, it will tell you how many attempts it took to guess correctly.

bannerAds