Home > Software design >  Keep on getting ValueError: invalid literal for int() with base 10: '1, 7'
Keep on getting ValueError: invalid literal for int() with base 10: '1, 7'

Time:12-04

I'm attempting to make a hangman like game, but when I run this code I currently have, I keep on getting errors, I've tried making new variables such as int1 and int2 but to no avail. Here is the code:

from nltk.corpus import words
import random

word_list = words.words()
password = random.choice(word_list)
finish = len(password)

print("The password has", len(password),"letters")
print(password)

while finish > 0:
    
    guess = input("Please enter a letter to see where it is in the word:  ")
    occur = password.count(guess)
    
    mylist = {', '.join([str(i) for i, c in enumerate(password) if c == guess])}
    print(mylist)

    int1 = [int(y) for y in mylist]

    int2 = [x 1 for x in mylist]
    print(ints)

    if len(guess) > 1 or len(guess) < 1:
        print("Enter 1 standard keyboard letter to see if it is in the word")
    
    elif guess in password:
         print(f"This letter is at position {', '.join([str(i) for i, c in enumerate(password) if c == guess])} in the word")
         finish = finish - occur
         password = password.replace(guess,'.')
         print("Only", finish, "letters left to guess")
         
    else:
        print("Try again")

What I want line 16-22 to do is first convert the elements of the list from string to integer, then print out the list, and then print out the same list again but with 1 added to every single element of the list. Here is the error I keep on getting:

Traceback (most recent call last):
  File "/Users/ARR2K18/Desktop/Hangman.py", line 29, in <module>
    int1 = [int(y) for y in mylist]
  File "/Users/ARR2K18/Desktop/Hangman.py", line 29, in <listcomp>
    int1 = [int(y) for y in mylist]
ValueError: invalid literal for int() with base 10: '1, 7'

Would like some help

CodePudding user response:

Your issue is here:

mylist = {', '.join([...])}
print(mylist)

int1 = [int(y) for y in mylist]

The ', '.join(...) is going to give you a result like "1, 7", and the set will look something like {"1, 7", "3, 4", ... }. Then when you call int() on one of those set elements you get the error shown.

The fix for this is probably to simply drop the join call and use the list comprehension alone.

  • Related