本当にwhileループが必要です。最初の推測が高すぎる場合、別のチャンスが得られますが、それはそれがあまりにも低いか等しいかどうかを調べるだけです。あなたの推測があまりにも低い場合は、2回目のチャンスが正しいことが必要です。
テストを続ける必要はないので、単純化することができますが、実際には設計段階でこれを行う必要があります。ここに私のバージョンは次のとおりです。
import random
# from random import randint << no need for this line
print("Welcome to guess the number!")
question = input("Do you want to play the game? ")
if question.lower() == "yes":
print("Sweet! Let`s begin!\nGuess the number between 1 and 10!")
number = random.randint(1, 10)
guess = None # This initialises the variable
while guess != number: # This allows continual guesses
guess = int(input("Take a guess!: ")) # Only need one of these
if guess > number:
print("Your guess is too high")
elif guess < number:
print("Your guess is too low")
else: # if it isn't <or> then it must be equal!
print("Your guess was correct!")
else:
# why do another test? No need.
print("Too bad! Bye!")
# No need for quit - program will exit anyway
# but you should not use quit() in a program
# use sys.exit() instead
今、私はあなたが、彼らはそれが権利を取得する前にプレイヤーが持っている推測の数のカウントを追加し、最後にあることを印刷示唆します!
編集:私のimport
のステートメントは@Denis Ismailajのステートメントとは異なります。 import
が1つしか必要ではないが、どちらの意見が異なっているかはどちらも同意する。私のバージョンでは、私はimport random
で、これはrandom.randint
と言う必要がありますが、他方ではrandint
としか言いようがありません。
小さなプログラムでは、あまり選択する必要はありませんが、プログラムは決して小さくなりません。 6,7,8以上のモジュールを簡単にインポートできる大きなプログラムでは、関数がどのモジュールから来るのかを追跡することが難しい場合があります。これは名前空間汚染として知られています。 randint
のようなよく知られている関数と混乱することはなく、関数の名前を明示的に指定すると簡単に戻すことができます。それは個人的な好みとスタイルの唯一の質問です。推測の数と
が追加:ここで
import random
print("Welcome to guess the number!")
question = input("Do you want to play the game? ")
if question.lower() == "yes":
print("Sweet! Let`s begin!\nGuess the number between 1 and 10!")
number = random.randint(1, 10)
guess = None
nrGuesses = 0 # Added
# Allow for continual guesses
while guess != number and nrGuesses < 6: # Changed
guess = int(input("Take a guess!: ")) # Only need one of these
nrGuesses += 1 # Added
if guess > number:
print("Your guess is too high")
elif guess < number:
print("Your guess is too low")
else: # if it isn't <or> then it must be equal!
print("Your guess was correct!")
else:
print("Too bad! Bye!")
print("Number of guesses:", nrGuesses) # Added
こんにちは、偉大なプログラムの世界へようこそ。私たちの世界では、例外が発生した場合、詳細な説明とスタックトレースで表現されています。 – spectras
'print( 'Sweet' ...'はインデントされている必要があり、 'question =="ならばそれを変更したい ".lower()' 'question.lower()==" yes "'。 – Jaco