# Python 3：猜数字

> 原文： [https://javabeginnerstutorial.com/python-tutorial/python-3-guess-the-number-2/](https://javabeginnerstutorial.com/python-tutorial/python-3-guess-the-number-2/)

现在，让我们编写一个脚本，该脚本实现一个基本的“猜数字”游戏。 游戏规则为：

*   用户选择是否要猜测 1 到 100 或 1 到 1000 之间的数字
*   根据数字范围，用户拥有固定数目的猜测
*   应用生成一个数字进行猜测
*   用户输入一个数字
    *   如果这是秘密号码，则应用祝贺用户并询问他/她是否想再玩一轮
    *   否则，应用会告诉用户密码是否小于或大于提供的密码
    *   猜测数增加
*   如果用户用尽了所有猜测，则应用告诉他/她的秘密号码，并询问用户是否要再玩一轮

如您所见，规则很简单，但实现起来似乎很复杂。 由您决定如何处理错误的输入类型（无数字）。

好吧，这并不像听起来那样困难。 让我们看一下我的解决方案的一些示例输出：

```java
Should the secret number between 1 and 100 or 1 and 1000? 100
You have chosen 100, you will have 7 guesses to find the secret number.
I have chosen the secret number...
What's your guess? 34
The secret number is higher...
What's your guess? 54
The secret number is higher...
What's your guess? 66
Congrats, you have Won!
The secret number was 66
Do you want to play another round? (yes / no) yes
Should the secret number between 1 and 100 or 1 and 1000? 1000
You have chosen 1000, you will have 10 guesses to find the secret number.
I have chosen the secret number...
What's your guess? 500
The secret number is lower...
What's your guess? 400
The secret number is lower...
What's your guess? 300
The secret number is higher...
What's your guess? 350
The secret number is higher...
What's your guess? 375
The secret number is lower...
What's your guess? 370
The secret number is lower...
What's your guess? 360
The secret number is higher...
What's your guess? 365
The secret number is lower...
What's your guess? 364
The secret number is lower...
What's your guess? 363
The secret number is lower...
Sorry, you lose.
The secret number was 362
Do you want to play another round? (yes / no) no
```

如您所见，当猜测用完时，应用不会停止，并且如果用户获胜或失败，它会显示一条消息。

让我们看一下代码。

```java
__author__ = 'GHajba'

import random

while True:
   while True:
       try:
           max_number = int(input('Should the secret number between 1 and 100 or 1 and 1000? '))
       except ValueError:
           print("This was not a number!")
           continue
       if max_number != 100 and max_number != 1000:
           continue
       else:
          break

   if max_number == 100:
       guess_count = 7
   else:
       guess_count = 10

   print('You have chosen {}, you will have {} guesses to find the secret number.'.format(max_number, guess_count))

   secret_number = random.randint(1, max_number)

   print('I have chosen the secret number...')

   guesses = 0

   while guess_count - guesses:
       try:
           guesses += 1
           guessed = int(input("What's your guess? "))
       except ValueError:
           continue
      if guessed == secret_number:
           print('Congrats, you have Won!')
           break
       elif guessed > secret_number:
           print('The secret number is lower...')
       else:
           print('The secret number is higher...')
   else:
       print("Sorry, you lose.")

   print("The secret number was ", secret_number)
   answer = ''
   while answer.lower() not in ['yes', 'no', 'y', 'n']:
       answer = input("Do you want to play another round? (yes / no) ")

   if 'no' == answer or 'n' == answer:
       break
```

如您所见，代码非常繁琐，因为我们包含许多循环来验证输入并处理主游戏循环。 也许您以后会发现此代码根本不可读。 为了解决这个问题，我们将学习函数，然后重构这部分代码以使用函数。

但是，此脚本也有一些替代解决方案。 例如，您可以将中间的`while`循环更改为`for`循环：

```java
for guesses in range(guess_count):
```

在这种情况下，循环遍历猜测范围，如果到达最后一个数字，则循环结束。

