py猜数编程怎么写

时间:2025-03-03 04:17:58 明星趣事

```python

import random

def guess_number_game():

number_to_guess = random.randint(1, 100)

num_guesses = 0

print("Welcome to the Guess the Number Game!")

print("I'm thinking of a number between 1 and 100. Can you guess it?")

while True:

guess = int(input("Enter your guess: "))

num_guesses += 1

if guess < number_to_guess:

print("Too low. Try again!")

elif guess > number_to_guess:

print("Too high. Try again!")

else:

print(f"Congratulations! You guessed the number in {num_guesses} tries.")

break

guess_number_game()

```

这个程序会随机生成一个1到100之间的整数,然后提示用户猜这个数是多少。用户每次输入一个数字,程序会根据这个数字与随机数的大小关系给出提示,直到用户猜对为止。