3

「GuessmyNumber」ゲームのコードをPython3で書いています。ただし、このバージョンでは、コンピューターはユーザーが秘密にしている番号を推測する必要があります。私はPythonとプログラミング全般に不慣れであり、少し助けていただければ幸いです。型変換に関連するエラーが発生します。エラーは次のとおりです。

    Traceback (most recent call last):
  File "C:\Users\Documents\python\GuessMyNumberComputer.py", line 16, in <module>
    response = input("Is the number" +guess +"? \n Press (y - yes, l - go lower, h - go higher)")
**TypeError: Can't convert 'int' object to str implicitly**

そしてここに私のコードがあります:

 import random

print("\t\t\t Guess My Number")
input("Think of a number between 1 and 100 and I will try to guess it. \nPress enter when you have thought of your number and are ready to begin.")
a = 1
b = 100
tries = 0

while 1==1:
    guess = random.randint(a,b)
    response = input("Is the number" +guess +"? \n Press (y - yes, l - go lower, h - go higher)")
    tries += 1
    if response == y:
        break

    elif response == l:
        b = response-1

    elif response == h:
        a = response+1


print("Aha! I guessed it! And it only took",tries,"tries!")
input("Press enter to exit.")                 

誰かがこのエラーで私を助けることができますか?私の本はこの分野をカバーしていないように思われるので、私がこれを読むことができるように、ウェブ上のいくつかのリンクを教えてもらえますか。

ありがとう。

4

3 に答える 3

3

intをstr()コンストラクターに渡して、文字列に変換するだけです。だからここに新しい行があります:

response = input("Is the number" + str(guess) +"? \n Press (y - yes, l - go lower, h - go higher)")
于 2012-12-10T03:57:59.143 に答える
0

format()異なる型から文字列を構築するときに使用する必要があります。それはあなたの意図をより明確にします。

response = input('Is the number {}? \n Press...'.format(guess))
于 2012-12-10T04:03:25.267 に答える
0

他の回答はすでにあなたTypeErrorに対処しているので、あなたが読むために何かを追加します:

Python 3.3 チュートリアル

于 2012-12-10T04:06:38.417 に答える