Python index error for hangman game program - python

This is a piece of the program for a game of hangman. I am trying to iterate through the hangman word and print the letter guessed by the user if it matches at that index. If it does not it will print an underscore. I am getting the following error for the second if condition: IndexError: string index out of range
while(guessTracker >= 0):
letterGuess= input("Enter a letter for your guess: ")
count=0
wordGuess=""
if letterGuess in hangmanWord:
while count<= len(hangmanWord):
if hangmanWord[count]==letterGuess:
wordGuess= wordGuess+ letterGuess
right= right+1
else:
wordGuess= wordGuess + "_ "
count+=1
print(wordGuess)

In Python (and most other programming languages) string indexes start at 0 so the last position is len(hangmanWord)-1.
You can fix it just by changing <= to <.

Try
while count<= len(hangmanWord)-1:
Because the string's length will never reach the real length (for example: if the word is "hangman", it has a length of 7, but the count starts from 0, and goes up to a maximum of 6, therefor not being able to ever reach the 7th char.

String indexes are from 0 to len(string)-1;
you just need to change your loop like this:
while count < len(hangmanWord):

Indexes are 0-based so you index a string from index 0 up to len(hangmanWord) - 1.
hangmanWord[len(hangmanWord)] will always raise an IndexError.
You should also give a look to the enumerate function that can help with that.
wordGuess = ["_"] * len(hangmanWord)
for index, letter in enumerate(hangmanWord):
if letterGuess == letter:
wordGuess[index] = letter
print("".join(wordGuess))

Related

String Index Out of Range when comparing characters

I am simply trying to compare one character in a string to its neighbor, but I keep getting a string index out of range error. I can't figure this out.
s = 'azcbobobegghakl'
current = ""
previous = ""
for letter in range(0,len(s)):
if s[letter] <= s[letter+1]:
current += s[letter]
print(current)
Thanks
The if statement was unnecessary. On the last iteration of the loop, s[letter+1] was throwing an error because that index of the string didn't exist. At that point, letter was equal to the length of your string, s. letter+1 was one higher than the length, so the index didn't exist.
There is no need to compare the value of letter to the length of s in the if statement because the loop would end before letter is greater than the length of s.
Solution:
s = 'azcbobobegghakl'
current = ""
previous = ""
for letter in range(0,len(s)):
current += s[letter]
print(current)
while #sedavidw is completely right pointing out the indexing issue, it is not a very pythonic way of doing such a comparison. I'd do something like:
current = ''.join(letter for letter, next_letter in zip(s, s[1:])
if letter <= next_letter)
I think you want to print a letter only if the previous one is less than the current one. The index out of bounds occur because the last index points to (l) but index + 1 points to nothing.
Here is my solution:
s = 'azcbobobegghakl'
current = ""
previous = ""
for letter in range(0,len(s)):
if letter + 1 < len(s): # this is important to prevent the index out of bounds error
if s[letter] <= s[letter+1]:
current += s[letter]
print(current)
Output: abbbeggak

how to reverse a sentence with a while loop

For an assignment, I need to use a while loop to reverse a list, and I just can't do it.
This is the sample code I have to help me get started:
sentence = raw_int (" ")
length = len(sentence) # determines the length of the sentence (how many characters there are)
index = length - 1 #subtracts one from the length because we will be using indexes which start at zero rather than 1 like len
while... #while the index is greater than or equal to zero continue the loop
letter = sentence[index] #take the number from the index in the sentence and assigns it to the variable letter
I need to use this in my solution.
sentence = raw_input(" ")
length = len(sentence)
index = length - 1
reversed_sentence = ''
while index >= 0:
#letter is the last letter of the original sentence
letter = sentence[index]
#make the first letter of the new sentence the last letter of the old sentence
reversed_sentence += letter
#update the index so it now points to the second to last letter of the original sentence
index = index - 1
print reversed_sentence
Because this is an assignment, I'm not going to give you the full code. But I will give you two 'hints'.
1) a sentenced is reversed if every character is 'flipped'. For example, 'I ran fast'-to flip this sentence first swap 'I' and 'f', then space and 's' and so on.
2) you can use syntax like:
Sentence[i], sentence[len(sentence)-i] = sentence[len(sentence)-i], Sentence[i]
This should definitely be enough to get you going.
You can do:
new_sentence = list()
sentence = list(raw_input(" "))
while sentence:
new_sentence.append(sentence.pop(-1))
else:
sentence = ''.join(new_sentence)

Beginner Issue; string index out of range

# word reverser
#user input word is printed backwards
word = input("please type a word")
#letters are to be added to "reverse" creating a new string each time
reverse = ""
#the index of the letter of the final letter of "word" the users' input
#use this to "steal" a letter each time
#index is the length of the word - 1 to give a valid index number
index = len(word) - 1
#steals a letter until word is empty, adding each letter to "reverse" each time (in reverse)
while word:
reverse += word[index]
word = word[:index]
print(reverse)
print(reverse)
input("press enter to exit")
Working to make a simple program that spells a user input word backwards and prints it back to them by "stealing" letters from the original and making new strings from them.
Trouble I'm having is this code spews back a string index out of range error at
reverse += word[index]
Help or a better way of achieving same result is mucho apreciado.
Reversing a word in python is simpler than that:
reversed = forward[::-1]
I wouldn't use a loop, it's longer and less readable.
While others have pointed out multiple ways of reversing words in Python, here is what I believe to be the problem with your code.
index always stay the same. Lets say the user inputs a four letter word, like abcd. Index will be set to three (index = len(word) - 1). Then during the first iteration of the loop, word will be reduced to abc (word = word[:index]). Then, during the next iteration of the loop, on the first line inside it (reverse += word[index]) you will get the error. index is still three, so you try to access index[3]. However, since word has been cut short there is no longer an index[3]. You need to reduce index by one each iteration:
while word:
reverse += word[index]
word = word[:index]
index -= 1
And here is yet another way of reversing a word in Python (Wills code is the neatest, though):
reverse = "".join([word[i-1] for i in range(len(word), 0, -1)])
Happy coding!
You're going to want to use the "range" function.
range(start, stop, step)
Returns a list from start to stop increasing (or decreasing) by step. Then you can iterate through the list. All together, it would look something like this:
for i in range(len(word) -1, -1, -1):
reverse += word[i]
print(reverse)
Or the easier way would be to use string slicing to reverse the word directly and then iterate through that. Like so:
for letter in word[::-1]:
reverse += letter
print(reverse)
With the way it is written now, it will not only print the word backwards, but it will also print each part of the backwards word. For example, if the user entered "Hello" it would print
o
ol
oll
olle
olleH
If you just want to print the word backwards, the best way is just
print(word[::-1])
It is because you are not changing the value of the index
modification:
while word:
reverse += word[index]
word = word[:index]
index-=1
print(reverse)`
that is you have to reduce index each time you loop through to get the current last letter of the word

Printing odd numbered characters in a string without string slicing?

I'm currently doing a project for my university, and one of the assignments was to get python to only print the odd characters in a string, when I looked this up all I could find were string slicing solutions which I was told not to use to complete this task. I was also told to use a loop for this as well. Please help, thank you in advance.
Here is my code so far, it prints the string in each individual character using a for loop, and I need to modify it so that it prints the odd characters.
i = input("Please insert characters: ")
for character in i:
print(character)
Please follow this code to print odd numbered characters
#Read Input String
i = input("Please insert characters: ")
#Index through the entire string
for index in range(len(i)):
#Check if odd
if(index % 2 != 0):
#print odd characters
print(i[index])
Another option:
a= 'this is my code'
count = 1
for each in list(a):
if count % 2 != 0:
print(each)
count+=1
else:
count+=1
I think more information would be helpful to answer this question. It is not clear to me whether the string only contains numbers. Anyway, maybe this answers your question.
string = '38566593'
for num in string:
if int(num) % 2 == 1:
print(num)
To extend on Kyrubas's answer, you could use-
string = '38566593'
for i, char in enumerate(string):
if i % 2 == 1:
print(char)
person = raw_input("Enter your name: ")
a = 1
print"hello " , person
print "total : " , len(person)
for each in list (person):
if a % 2 ==0:
print "even chars : " , (each)
a+=1
else:
a+=1
s = raw_input()
even_string=''
odd_string=''
for index in range(len(s)):
if index % 2 != 0:
odd_string = odd_string+s[index]
else:
even_string = even_string+ (s[index])
print even_string,odd_string
Try this code. For even index start you can use range(0, len(s), 2).
s = input()
res = ''
for i in range(1,len(s),2):
res +=s[i]
print(res)
When we want to split a string, we can use the syntax:
str[beg:end:jump]
When we put just one number, this number indicates the index.
When we put just two numbers, the first indicates the first character (included) and the second, the last character (excluded) of the substring
You can just read the string and print it like this:
i = input("Please insert characters: ")
print(i[::2])
When you put str[::] the return is all the string (from 0 to len(str)), the last number means the jump you want to take, that meaning that you will print the characters 0, 2, 4, etc
You can use gapped index calling. s[start:end:gap]
s = 'abcdefgh'
print(s[::2])
# 'aceg'
returning the characters with indexes 0, 2, 4, and 6. It starts from position 0 to the end and continues with a gap of 2.
print(s[1::2])
# 'bdfh'
Returning the characters with indexes 1, 3, 5, and 7. It starts from position 1 and goes with a gap of 2.

How can I understand this For-Loop? (Difficulty fully understanding For-Loops)

In my Python textbook they have created a 'Hangman' game. Full source: http://pastebin.com/k1Fwp7zJ
I am having tremendous difficulty understanding the following code snippet:
new = ""
for i in range(len(word)):
if guess == word[i]:
new += guess
else:
new += so_far[i]
so_far = new
I don't know exactly what "i" is. I also don't know how to "say"/imagine the For-Loop in English. I cannot understand/imagine what is happening in this code segment, even though I've done all of the preparation in this chapter and gotten everything correct so far.
In my planning/algorithm for this part of the Hangman game, I've written:
*"Go through each character of the word and check if the guessed letter is in the word. If the guessed letter is in the word, note its position(s).
Then go to the above positions in "so_far", and replace with the guessed letter."*
I literally have a headache trying to understand this section of code. When I try to write the hangman game myself, I always get stuck here and I have no idea how to do it.
Maybe someone has been in a similar situation as me. Can someone explain what this For-loop means? And perhaps a way to understand the rest of the code here?
"I don't know exactly what i is"
i is the name to which each item in range is assigned. The first time through the loop, i == 0. The second time, i == 1, and so on.
"I don't know how to "say"/imagine the for-Loop in English."
A for loop in Python has two parts; the name(s) to assign to, and the iterable(s) to iterate through. For each value in the iterable, the loop runs once*, assigning that value to the provided name.
Your example is a relatively simple one:
for i in range(...):
Here range(start[, stop[, step]]) provides the integers in each step from start to stop (not inclusive). You have only a stop, so the default start=0 and step=1 are used, giving:
range(n) ~= [0, 1, 2, ..., n-1, n]
Each of these values in assigned, in turn, to the name i, allowing you to access them inside the loop.
* unless you break out, return or an error is raised
new = ""
This line creates an empty string
for i in range(len(word)):
In this line the code tells the interpreter for every number in the range 0 up to the length (obtained by the len() funciton) of word -1 do the code that follows.
For example len('Thing') would be 5. Now the interpreter will do whatever is inside the for loop 5 times if the code was:
for i in range(len('thing')):
print('Hello, world')
Hello, world would be printed 5 times. In Python you don't need to increment i like you do in other languages. So when the loop starts i == 0 after it goes through the if/else block it will be incremented to 1 automatically.
if guess == word[i]:
This line checks to see if the variable guess is equal to the value of word at index i. For example if word = 'thing' then word[0] would be t. Computers start counting from 0 not 1, so word[4] would be g.
new += guess
This line is shorthand for new = new + guess. Since we are working with strings the + operator wil concatenate them, or glue them together. For example 'a' + 'b' would be ab.
else:
This line indicates what to do if the if condition is not met. For example:
if some_number > 10:
print('hello')
else:
print('Bye')
If some_number was greater than 10 hello would print. If not Bye would print.
new += so_far[i]
This line concatenates new and whatever is at index i in so_far.
so_far = new
This sets so_far equal to new.
In your program, Python's range() function takes an integer (here, the length of the word you're trying to guess) and returns a list of integers from 0 to that number.* So:
word = "example"
len(word) //equals 7
range(len(word)) //returns [0,1,2,3,4,5,6]
Lists in Python are iterable data types. This means that you can iterate over the elements, i.e. move over the elements one at a time and do something to each one. First it sets i to 0, then does whatever is contained in the body of the for-loop. Then it sets i to 1 and does whatever is contained in the body of the for loop again. And it keeps going until it reaches the end of the list. So with your example:
word = "example"
for i in range(len(word))
You're telling Python to do something on each element i in the list [0,1,2,3,4,5,6]. There's nothing special about "i" here. You can name it whatever you want, but it's just a conventional shorthand notation used to reference the element later. For example:
for i in range(3):
print "The number is " + i
This prints:
The number is 0
The number is 1
The number is 2
In Python, strings can be accessed by index. So for example:
word = "example"
word[0] = "e"
word[1] = "x"
. . .
Couple this with the for-loop, and you have:
word = "example"
myWordLength = len(word)
for i in range(myWordLength):
print "The letter is " + word[i]
And this with print:
The letter is e
The letter is x
The letter is a
The letter is m
The letter is p
The letter is l
The letter is e
Range(), for-loops and lists can do lots of other things too but hopefully that helps you understand the assignment.
for loops follow this simple design:
Let's break this line down:
for i in range(len(word)):
First, let's look at:
for i
The keyword for is known as a loop. It will repeat/iterate the same chunk of code until the condition is met. The i is the current variable(in this case, numeric variable). Imagine someone say, write the numbers from 1 to 10, then your i will go from the number 1 to the number 10.
in
The keyword in will be declaring the range of values the previous variable i will equal. Let's break down this:
range(len(word))
This translate to the range values of the length of the variable word. Say the the word equals to "hello", then length is 5. This means the range of 5 is 0,1,2,3,4 (range excludes the final value).
Basically, this:
for i in range(len(word)):
Means:
iterate the variable `i` from the range of the length of the the variable `word`.
A simple test to see what i is to change the code to:
new = ""
for i in range(len(word)):
print i #this will print the values
if guess == word[i]:
new += guess
else:
new += so_far[i]
so_far = new
Remember, there are plenty of tutorials online:
Link 1
Link 2
Link 3

Categories

Resources