【解決方法】乱数を生成し、それを見つけるための推測の量を制限する Python コードを作成するにはどうすればよいでしょうか?

プログラミングQA


このコードは、乱数を生成して、自分が高いか低いかを知らせることを目的としています。 それを見つけるために行われる推測の量を制限できるようにしたいと考えています。

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")

そのようなものが役立つはずです。

コメント

タイトルとURLをコピーしました