2017-01-31 1 views
6

저는 파이썬을 배우고 연습을하고 있습니다. 그 중 하나는 투표 시스템을 작성하여리스트를 사용하는 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'

얻을하지만 여기에 모든 문자열이없는, 모든 변수는 정수이다. 당신은 수치 연산을 수행하기 위해에 int 객체에 해당 입력 문자열을 캐스트 할 필요가 있도록

답변

10

변경

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

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

에 당신은 문자열로 콘솔에서 입력을 받고있다.

1

입력 기능을 사용하면 자동으로 문자열로 바뀝니다. 당신은 갈 필요 : 정수 (int) 형의 값으로 입력을 전환

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

9

당신이 정수로 문자열을 변환 할 int 방법을 사용해야합니다 있도록 문자열을 반환합니다 Python3.x input 사용하는 경우 . 이 도움이

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

희망을 : 당신이 int로 문자열을 변환 할 경우

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.

, 그것은 trycatch를 사용하는 좋은 방법입니다.

관련 문제