1. No Profile Picture
Registered User
Devshed Newbie (0 - 499 posts)

Join Date
Dec 2013
Posts
2
Rep Power
0

#### Hangman Beginner Question

Hey all,

This is my first post, so first off... Hello!

I'm less than a novice with Python and I've been working through a book called Python Programming for the Absolute Beginner and I'm up to a part that has me creating a version of Hangman with Python. There full code can be found:

I only have a question about a specific part of the code:

Code:
```if guess in word:
print("\nYes!", guess, "is in the word!")

# create a new so_far to include guess
new = ""
for i in range(len(word)):
if guess == word[i]:
new += guess
else:
new += so_far[i]
so_far = new
else:
print("\nSorry,", guess, "isn't in the word.")
wrong += 1```
Can someone explain to me step by step, as if I'm a preschooler, exactly what this section of the code is doing? I know it's adding the users correct guess to so_far, but how is it doing that? I suppose it's the "for i in range(len(word)):" up until "so_far = new" that's losing me.

Any help would be appreciated. Thanks!

P.S.
This isn't for a class or anything, just learning on my own.

2. if guess in word: good guess action else: wrong action

You comprehended that part.

good guess action:

for each character in goal word
construct a new so_far from the current so_far and the new letter.

If the character in goal matches the guess use the guess, else copy the character from current so_far.

with word = 'PYTHON', so_far = '---H--', and guess = 'O'
Code:
```i  word  so_far  new  source

0   P      -      -   so_far
1   Y      -      -   so_far
2   T      -      -   so_far
3   H      H      H   so_far
4   O      -      O   guess
5   N      -      -   so_far```
Code:
```\$ python3
Python 3.3.2+ (default, Oct  9 2013, 14:50:09)
[GCC 4.8.1] on linux
>>> word = 'PYTHON'
>>>
>>> print(word)
PYTHON
>>> print(len(word))
6
>>> print(range(len(word)))
range(0, 6)
>>> print(list(range(len(word))))
[0, 1, 2, 3, 4, 5]
>>> for i in list(range(len(word))):
...     print(i, word[i])
...
0 P
1 Y
2 T
3 H
4 O
5 N
>>> so_far = '---H--'
>>> guess = 'o'.upper()
>>> for i in range(len(word)):
...     use_guess = guess == word[i]
...     print('{}   {}      {}      {}   {}'.format(i, word[i], so_far[i], (so_far[i], guess,)[use_guess], ('so_far', 'guess',)[use_guess]))
...
0   P      -      -   so_far
1   Y      -      -   so_far
2   T      -      -   so_far
3   H      H      H   so_far
4   O      -      O   guess
5   N      -      -   so_far
>>> print('i  word  so_far  new  source')
i  word  so_far  new  source
>>>```
3. No Profile Picture
Registered User
Devshed Newbie (0 - 499 posts)

Join Date
Dec 2013
Posts
2
Rep Power
0