Welcome!

By registering with us, you'll be able to discuss, share and private message with other members of our community.

SignUp Now!
  • Guest, before posting your code please take these rules into consideration:
    • It is required to use our BBCode feature to display your code. While within the editor click < / > or >_ and place your code within the BB Code prompt. This helps others with finding a solution by making it easier to read and easier to copy.
    • You can also use markdown to share your code. When using markdown your code will be automatically converted to BBCode. For help with markdown check out the markdown guide.
    • Don't share a wall of code. All we want is the problem area, the code related to your issue.


    To learn more about how to use our BBCode feature, please click here.

    Thank you, Code Forum.

Python Expected type 'Sized', got 'int' instead

skifli

Backend Developer
Hi. I'm coding a hangman game in Python & I've been getting an error that I can't figure out how to get rid off. Basically, after I take the user's letter, I create a counter that goes from 0 to the length of the word. However, since Python uses the number 0 first, instead of 1, I have to do the user's guess - 1. If I don't it'll give an index out of range error. But when I run it it gives me an error saying:

'
Traceback (most recent call last):
File "C:\Users\Administrator\Documents\Coding\Games\Hangman.py", line 46, in <module>
for counter in range(len(0, user_guess - 1)):
TypeError: unsupported operand type(s) for -: 'str' and 'int'
'
Any help would be appreciated. Here is the part of the code the error is in:
[CODE lang="python" title="Code" highlight="4"]user_guess = input("Enter a letter: ")

for counter in range(len(user_guess - 1)):
if user_guess == word[counter]:
user_word_guesses[counter] = user_guess[/CODE]
 
Solution
Yeah, but you are doing len(user_guess - 1), which I would think should instead be len(user_guess) - 1 right? Just taking a guess as I don't code in Python, hopefully it helps.
I think that python is treating the user_guess as a string, so when you try to do the subtraction it fails because you can't subtract a number from a string. Try casting the string as an int: https://www.w3schools.com/python/python_casting.asp

I'm sorry, I think you misunderstood. The user's input is meant to be a string, not an integer. The ' -1 ' part is not meant to be applied onto the string, but rather the length of the string in characters, which is got by doing:[CODE lang="python" title="COde" highlight="1"]len(user_input) # len() means get length[/CODE]
 
Yeah, but you are doing len(user_guess - 1), which I would think should instead be len(user_guess) - 1 right? Just taking a guess as I don't code in Python, hopefully it helps.
 
Solution

Latest posts

Buy us a coffee!

Back
Top Bottom