I’m learning python and working on exercises. One of them is to code a voting system to select the best player between 23 players of the match using lists.
I’m using Python3.
My code:
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')
I get
TypeError: ‘<=’ not supported between instances of ‘str’ and ‘int’
But I don’t have any strings here, all variables are integers.
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
Change
vote = input('Enter the name of the player you wish to vote for')
to
vote = int(input('Enter the name of the player you wish to vote for'))
You are getting the input from the console as a string, so you must cast that input string to an int object in order to do numerical operations.
Method 2
If you’re using Python3.x input will return a string,so you should use int method to convert string to integer.
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.
By the way,it’s a good way to use try catch if you want to convert string to int:
try: i = int(s) except ValueError as err: pass
Hope this helps.
Method 3
input() by default takes the input in form of strings.
if (0<= vote <=24):
vote takes a string input (suppose 4,5,etc) and becomes uncomparable.
The correct way is: vote = int(input("Enter your message")will convert the input to integer (4 to 4 or 5 to 5 depending on the input)
Method 4
When you use the input function it automatically turns it into a string. You need to go:
vote = int(input('Enter the name of the player you wish to vote for'))
which turns the input into a int type value
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0