2017-01-31 25 views
6

私はPythonを学習し、演習を行っています。それらの1つは、リストを使用して試合の23人の選手の間で最優秀選手を選ぶ投票システムをコードすることです。TypeError: '<='は 'str'と 'int'のインスタンス間ではサポートされていません

私はPython3を使用しています。

マイコード:

players= [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0] 
vote = 0 
cont = 0 

while(vote >= 0 and vote <23): 
    vote = input('Enter the name of the player you wish to vote for') 
    if (0 < vote <=24): 
     players[vote +1] += 1;cont +=1 
    else: 
     print('Invalid vote, try again') 

私は

TypeError: '<=' not supported between instances of 'str' and 'int'

を取得しかし、私はここに任意の文字列を持っていない、すべての変数は整数です。

vote = int(input('Enter the name of the player you wish to vote for')) 

答えて

10

変更

vote = input('Enter the name of the player you wish to vote for') 

あなたは文字列としてコンソールからの入力を取得しているので、あなたは、数値演算を行うためにintオブジェクトにその入力文字列をキャストする必要があります。

1

入力機能を使用すると、自動的に文字列に変換されます。あなたは移動する必要があります。int型の値に入力をオン

vote = int(input('Enter the name of the player you wish to vote for')) 

9

あなたは文字列を整数に変換するために、intメソッドを使用する必要がありますので、あなたは、文字列を返しますPython3.x input使用している場合。ところで

Python3 Input

If the prompt argument is present, it is written to standard output without a trailing newline. The function then reads a line from input, converts it to a string (stripping a trailing newline), and returns that. When EOF is read, EOFError is raised.

、それはあなたがintに文字列を変換したい場合はtrycatchを使用するための良い方法です:

try: 
    i = int(s) 
except ValueError as err: 
    pass 

は、この情報がお役に立てば幸いです。

関連する問題