Python Forum

Full Version: Invalid syntax: string index out of range
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
import time
import sys

# introduction to  the game

print("You are playing the guessing game! To win you must guess the word, within the 5 lives you are given. If you use all 5 lives, you lose!")

time.sleep(2)

print("Type 'yes' when your ready to play")

time.sleep(0.5)


#behind the scenes stuff

word = 'dog'
lives = 5
win = 0

  




# game

ans = input("Ready: ")

while ans == 'yes':
  user = input("Please guess a letter: ")
  if user == word[1] or word[3] or word[2]:
    print("Well done! You guessed a letter correctly!")
    win = win + 1
    time.sleep(1)
    print("You have", lives, "lives!")
    time.sleep(2)
    
    
    if user != word[1] or word[3] or  word[2]:
      print("Wrong! You guessed incorrectly!")
      time.sleep(1)
      lives = lives - 1
      print("You have", lives, "lives remaining!")
      time.sleep(2)


  #this is for if you lose or win

  if win == 3:
    print("You've won!")
    time.sleep(0.5)
    print("Want to play again?")
    ans = input("Yes or no: ")
  
  
  elif lives == 0:
    print("You lose!")
    time.sleep(0.5)
    print("Want to play again?")
    ans = input("Yes or no: ")


if ans == 'no':
  sys.exit
 
FOR SOME REASON THE INVALID SYNTAX IS COMING UP, I THINK THERE ARE OTHER SECTIONS OF THIS CODE INCORRECT, HOWEVER I JUST SIMPLY DON'T UNDERSTAND WHAT THE ERROR MESSAGE MEANS (INVALID  SYNTAX -  STRING INDEX OUT OF RANGE).

THANKS AND YES I AM NEW TO THE FORUM,

DARKREAPER1959
1. Read the forum rules
2. Post the full traceback
and
3. Don't use ALL CAPS, that is perceived as shouting
I have read the rules, sorry the caps was to make my text  stand out, I did not realise  that the code  and text is separated, my bad, I know now. I have supplied the code and given the error, here I'll copy and paste the full error (it was on python 3):

Traceback (most recent call last):
 File "python", line 32, in <module>
IndexError: string index out of range
indexes are zero-based. so in this case there is no index 3.
Also your statement
if user == word[1] or word[3] or word[2]:
even after correction for the index will always evaluate to TRUE

http://stackoverflow.com/documentation/p...1370259599
This is your error line
if user == word[1] or word[3] or word[2]:
should be:
if user == word[1] or user == word[3] or user == word[2]:

Plus index out of range
thanks guys, really helped..
What's even happening in this thread?  All of the quotes/code snippets/error messages are completely unrelated to the original post...

*edit* nevermind.  There was so much whitespace, I thought the OP only posted 6 lines of code.