编写函数模拟猜数游戏。系统随机产生一个数,玩家来猜,系统根据玩家的猜测进行提示,玩家可以根据系统的提示对下一次的猜测进行适当调整
时间: 2023-02-24 22:38:45 浏览: 755
以下是用 Python 实现的代码:
```
import random
def guess_number_game():
number = random.randint(1, 100)
guess = None
attempts = 0
print("Welcome to the Guess the Number game!")
print("I'm thinking of a number between 1 and 100.")
while guess != number:
try:
guess = int(input("What's your guess? "))
except ValueError:
print("Invalid input. Please enter an integer.")
continue
attempts += 1
if guess < number:
print("The number is higher.")
elif guess > number:
print("The number is lower.")
else:
print("You got it in {} attempts!".format(attempts))
if __name__ == "__main__":
guess_number_game()
```
在运行代码之前,系统会随机产生一个数字,玩家需要猜测这个数字,系统会根据玩家的猜测进行提示,如果玩家的猜测比随机产生的数字大,系统会告诉玩家,“The number is lower.”,如果玩家的猜测比随机产生的数字小,系统会告诉玩家,“The number is higher.”,直到玩家猜中数字为止。