以下是示例代码:
import random
def guess_number():
secret_number = random.randint(1, 100)
guess = None
attempts = 0
print("Welcome to the Guess the Number game!\n")
while guess != secret_number:
try:
guess = int(input("猜一个介于1和100之间的数字: "))
if guess < 1 or guess > 100:
raise ValueError
except ValueError:
print("输入无效。请输入一个介于1和100之间的数字。")
continue
attempts += 1
if guess < secret_number:
print("太小了!再试一次。")
elif guess > secret_number:
print("太大了!再试一次。")
else:
print(f"祝贺你猜到了 {secret_number} 一共 {attempts} 尝试.")
guess_number()
描述信息: