I'm new to Python, and have been doing online tutorials. Python is also my first programming language, I know no others, except for html and css, which don't really count.
I am trying to get through a tutorial that teaches how to make a hangman game.
Here is the tutorial:
Hangman
And here is the source code to the game:
Source Code of Hangman Game
***
alright, so what is my difficulty exactly? My difficulty is in understand how the colon functions as a slice within list indexes.
I'll give you an an example of a simplified piece of code I took from the hangman tutorial:
secretWord = 'monkey' length = len(secretWord) # this equals 6 blanks = '_' * len(secretWord) # this produces 6 blanks for i in range(length): # i = [0, 1, 2, 3, 4, 5] x = blanks[:i] print(x) # printing X causes a list of only 5 items. Why? Why aren't there six items?
So when you run this code, you'll find that it produces a list of 5 items. The first item is a single blank, the second is two blanks, the third is three blanks, and so on.
But it stops at 5 blanks. Why? The range is clearly from 0 to 5, which means you have six instances. Zero should produce a single blank, one should produce then next blank, then two, three, right up to 5, which would equal 6 blanks in total.
Now, to make matters even more confusing, please observe what happens when I put the colon on the right side of the list index:
secretWord = 'monkey' length = len(secretWord) # this equals 6 blanks = '_' * len(secretWord) # this produces 6 blanks for i in range(length): # i = [0, 1, 2, 3, 4, 5] x = blanks[i:] print(x) # printing X causes a list of only 5 items. Why? Why aren't there six items?
This time the list of blanks conforms to what I would actually expect, you have 6 list items. The first list item is string of 6 blanks, then next line down is a string of 5 blanks, then 4 blanks, and so on, right down to the last single blank. This makes sense.
So how come when the colon is placed on the left side of a list index, it fails to conform to logic one would expect?


Sign In
Create Account


Back to top









