[Tutor] dont understand part of a code
Alan Gauld
alan.gauld at yahoo.co.uk
Sat Jul 2 08:28:31 EDT 2016
On 02/07/16 11:46, Minhaj Ahmed via Tutor wrote:
> have underlined the part of code I do not understand and why it is there.
The mailing list is plain text so formatting like underline
doesn't show up. Fortunately you added a comment too...
> so_far = "-" * len(word)
so_far is whats printed as the result so far.
> used = []
used is the letters input so far
> while wrong < MAX_WRONG and so_far != word:
> print(HANGMAN[wrong])
> print("\nYou've used the following letterss:\n",used)
> print("\nSo far,the word is:\n", so_far)
> guess = input("\nEnter your guess: ")
> guess = guess.upper()
>
> while guess in used:
> print("You've already guessed the letter",guess)
...
> if guess in word:
> print("\nYes",guess,"is in the word!")
>
> new = ""
> for i in range(len(word)):
> if guess == word[i]:
> new += guess
> * else:*
> * new += so_far[i] # why is there a else code here?*
The else part is needed so that when the guess is noyt at the given
position the current value of so_far is put into new.
Lets assume the word is python
lets assume sop_far contains
____o_
And you guess y
On the first letter new should equal _
So because y is not the first letter the if clause is false
so the else is selected and new[0] becomes so_far[0], ie '_'
new = '_'
Now on the next index i = 1
guess == word[1] is true
so the if part executes setting new[1] to guess (ie to 'y')
new now equals '_y'
Now on the next index i = 2
guess == word[2] is false so the el;se gets selected
setting new[2] to so_far[2] = '_'
new now equals '_y_'
and so on.
new[i] either acquires the value of guess or so_far[i]
(remember that guess may appear more than once...)
> so_far = new
Finally so_far is replaced with the final value of new.
There are arguably easier ways of doing this using lists
of characters rather than strings but this works.
--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos
More information about the Tutor
mailing list