2017-11-19 10 views
0

私はnumCheck()関数のnumとuserNumの両方が文字列で関数でなければならないため、数字を推測する小さなゲームのスクリプトを作成しています。他のものは、現時点で働くか、完璧されない場合があること"TypeError: '関数'オブジェクトは文字列にサブスクリプトできませんか?

==================== RESTART: /home/pi/Desktop/cowbull.py ==================== 
Random number is: 8104 
Choose a number between 1000 and 9999: 5555 
Traceback (most recent call last): 
    File "/home/pi/Desktop/cowbull.py", line 47, in <module> 
    gameLoop() 
    File "/home/pi/Desktop/cowbull.py", line 43, in gameLoop 
    numCheck(num, userNum) 
    File "/home/pi/Desktop/cowbull.py", line 30, in numCheck 
    if userNum[i] == num[i]: 
TypeError: 'function' object is not subscriptable 
>>> 

ますが、私だけを把握しようとしている:

import random 

def num(): 
    """Returns a number between 1000 and 9999.""" 
    num = str(random.randint(1000, 9999)) 
    print("Random number is: " + num) #for testing purposes 
    return num 

def userNum(): 
    """Asks user for a number between 1000 and 9999.""" 
    while True: 
     try: 
      userNum = int(input("Choose a number between 1000 and 9999: ")) 
     except ValueError: 
      print("This isn't a number, try again.") 
      continue 
     if userNum < 1000 or userNum > 9990: 
      print("Your number isn't between 1000 and 9999, try again.") 
      continue 
     else: 
      break 
    userNum = str(userNum) 
    return userNum 

def numCheck(num, userNum): 
    """Checks the number of cows and bulls.""" 
    cow = 0 
    bull = 0 
    for i in range(0, 3): 
     if userNum[i] == num[i]: 
      cow += 1 
     else: 
      bull += 1 
    print("You have " + str(cow) + " cow(s) and you have " + str(bull) + " bull(s).") 
    return cow 

def gameLoop(): 
    """Loops the game until the user find the right number.""" 
    num() 
    cow = 0 
    if cow < 4: 
     userNum() 
     numCheck(num, userNum) 
    else: 
     print("Congratulation, You found the right number!") 

gameLoop() 

私は、スクリプトを実行したときに私が得るエラーは以下のとおりです。このエラーのロジックは私が続けることができます。

ありがとうございました!

def gameLoop(): 
    """Loops the game until the user find the right number.""" 
    num() 
    cow = 0 
    if cow < 4: 
     userNum() 
     numCheck(num, userNum) 
    else: 
     print("Congratulation, You found the right number!") 

あなたはuserNum()という名前の関数を呼び出していますが、変数にその戻り値を割り当てない:

+2

あなたは 'userNum'という名前の関数を持っていて、' numCheck'関数のパラメータと同じ名前を使用しています。つまり、あなたの問題です。解決策:これらの名前の1つを変更します。 – Abdou

答えて

0

はここにあなたの関数gameLoopです。次の行では、numCheckの引数としてuserNumを引数として渡します。 userNumは前の行の関数だったので、今でも関数でなければなりません(関数を引数として別の関数に渡すことはPythonではまったく正当です)。

戻り値をuserNumから新しい変数に割り当てる必要があります。その後numCheckに、その変数を渡す:

 x = userNum() 
     numCheck(num, x) 

あなたが機能numとまったく同じ間違いをしました。 numuserNumを文字列にしたい場合でも、実際には両方とも関数です。両方の関数return文字列ですが、後で使用するために返された値を新しい変数に割り当てる必要があります。

アブドーのコメントは、同じ変数名を使って別のものを意味するのは紛らわしいというのは正しいです。

+0

それはそれを解決した、ありがとう! – Alex

+0

答えを受け入れるにはちょっと時間をかけてください。 –

関連する問題