如何编写生成随机数并限制查找随机数的猜测量的 Python 代码?

编程

[ad_1]

该代码旨在能够生成一个随机数并告诉您您的分数是更高还是更低。 我希望能够限制找到它的猜测数量。

Python
import random
MAX_NUM = 100
max_tries_allowed = 10
print("\tWelcome to 'Guess My Number !'")
print(f"\nI'm thinking of a number between 1 and {MAX_NUM}")
print("Try to guess it in as few attempts as possible. \n")
# Set the initial values
the_number = random.randrange(MAX_NUM) + 1
guess = None
tries = 0
#guessing loop
while (guess != the_number):
 guess = int(input("Take a guess: "))
 if (tries == max_tries_allowed):
  print("You lose")
 elif (guess > the_number):
   print("Lower...")
 else:
   print("Higher...")
 tries += 1
print("You guessed it! The number was ", the_number)
print("And it only took you ",tries, " tries!\n")
input("\n\nPress the Enter key to exit")

我尝试过的:

我是一名初学者编码员,但我已经有了可以运行的基本程序,但唯一不能的是所做的猜测数量有限。

解决方案1

你对此非常接近。 您的 while 循环条件需要扩展,以便它不仅仅查看数字是否与猜测匹配。 它还需要检查您是否超过了允许的最大尝试次数。 像这样重新排列 while 子句:

found = false
while (found == false and tries < max_tries_allowed)
  guess = int(input("Take a guess: "))
  tries += 1
  if (guess = the_number):
    found = true
  if (guess > the_number):
    print("Lower...")
  elif (guess < the_number):
    print("Higher...")
  else:
    found = true
if (found == false):
  print("You didn't find the number")

类似的东西应该有帮助。

[ad_2]

コメント

标题和URL已复制