私は練習のための簡単な推測ゲームを作った。プログラムはエラーなしで機能していますが、指定された出力が間違った値です。ここで 出力数が正しくありません
はコードです:import random
welcome_phrase = "Hi there. What's your name?"
print("{:s}".format(welcome_phrase))
user_name = input("Name: ")
print("Hey {:s}, I am Crash. Let's play a game. I am thinking of a number between 1 and 20. Can you guess the number?".format(user_name))
attempts = 5
secret_num = random.randint(1,20)
for attempt in range (attempts):
guess = int(input("Guess the number: "))
if guess > secret_num:
print("Your guess is higher than the number. Try again")
elif guess < secret_num:
print("Your guess is lower than the number. Try again.")
else:
print("Well done! {:d} is the right number.".format(guess))
print("It took you {:d} attempts.".format(attempt))
break
if guess != secret_num:
print("Sorry, you have used up all your chances.")
print("The number was {:d}".format(secret_num))
そして、ここで出力されます:あなたは3つの試みがなされたことは明らかであるにもかかわらず、上記の画像で見ることができるように
正しい数を推測するために、Pythonは2回しかカウントしませんでした。誰も私にこれを解決する方法を教えてもらえますか?
コピーしてここにコンソール出力を貼り付けてください。また、Pythonは** 0インデックスの**言語なので、試行0,1&2は合計で –
の 'range'が3回になることに注意してください。 – Matthias
whileループとbreak文を使用する方が良いでしょう –