簡単な推測ゲームでユーザーが入力した推測の数を追跡する必要があります。
私はattempts = 0を使用して、試行回数を=試行+1に設定しようとしました。これを行っても、ユーザーが複数回の試行で推測した場合でも、コードは「1回の試行で推測しました」と出力します。
コード:
attempts = 0;
print("Hello, welcome to the game. You will be choosing a number
between 1 and 100. You can only guess up to 10 times.")
for tries in range(tries_allowed):
print("You only get 10 tries.")
break
while attempts < 10:
guess = int(input("Please guess a number"));
attempts_used= attempts + 1;
if guess > random_number:
print("Guess is too high, try a smaller number");
elif guess < random_number:
print("Guess is too low, try a higher number");
elif guess == random_number:
attempts_used=str(attempts_used)
print("Correct- you win in", attempts_used, "guesses");
exit();
else:
if tries_allowed == 10:
print("You failed to guess in time")
my_list= [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
my_list.append(attempts_used)
print(my_list)
コードを少しクリーンアップ+=
し、スクリプトで機能するカウント方法を示します。他の人が言っているように、元のコードは、attempts_used
単純attempts + 1
にattempts
0のままであるまったく新しい変数を作成しています。
また、可能性がありattempts = attempts + 1
、+=
同じことを意味します。
印刷目的でPythonでint
aを作成するstr
ために、別の変数に格納する必要はありませんstr()
。文字列を個別に使用する予定がない限り、変数を呼び出すだけです。
import random
random_number = random.randint(1,100)
attempts = 0
tries_allowed = 10
print("Hello, welcome to the game. You will be choosing a number between 1 and 100")
print("You only get " + str(tries_allowed) + " tries.")
my_list = []
while attempts < tries_allowed:
guess = int(input("Please guess a number: "))
if guess in my_list:
print("You have already guessed " + str(guess))
continue
attempts += 1
my_list.append(guess)
if guess > random_number:
print("Guess is too high, try a smaller number")
elif guess < random_number:
print("Guess is too low, try a higher number")
elif guess == random_number:
print("Correct- you win in", str(attempts), "guesses")
break
else:
if attempts == 10:
print("You failed to guess in time")
for item in my_list:
print(item)
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加