Printing Parallel Tuples in python
<p>I'm trying to make a word guessing program and I'm having trouble printing parallel tuples. I need to print the <code>"secret word"</code> with the corresponding hint, but the code that I wrote doesn't work. I can't figure out where I'm going wrong.</p>

<p>Any help would be appreciated :)</p>

<p>This is my code so far:</p>

<pre><code>import random

Words = ("wallet","canine")
Hints = ("Portable money holder","Man's best friend")
vowels = "aeiouy"
secret_word = random.choice(Words)
new_word = ""


for letter in secret_word:
    if letter in vowels:
        new_word += '_'
    else:
        new_word += letter

maxIndex = len(Words)

for i in range(1):
        random_int = random.randrange(maxIndex)
print(new_word,"\t\t\t",Hints[random_int])           
</code></pre>

<p>The issue here is that <code>random_int</code> is, as defined, random. As a result you'll randomly get the right result sometimes.</p>

<p>A quick fix is by using the <code>tuple.index</code> method, get the index of the element inside the tuple <code>Words</code> and then use that index on <code>Hints</code> to get the corresponding word, your print statement looking like:</p>

<pre><code>print(new_word,"\t\t\t",Hints[Words.index(secret_word)]) 
</code></pre>

<p>This does the trick but is clunky. Python has a data structure called a dictionary with which you can map one value to another. This could make your life easier in the long run. To create a dictionary from the two tuples we can <code>zip</code> them together:</p>

<pre><code>mapping = dict(zip(Words, Hints))
</code></pre>

<p>and create a structure that looks like:</p>

<pre><code>{'canine': "Man's best friend", 'wallet': 'Portable money holder'}
</code></pre>

<p>This helps. </p>

<p>Another detail you could fix is in how you create the <code>new_word</code>; instead of looping you can use a comprehension to create the respective letters and then <code>join</code> these on the empty string <code>""</code> to create the resulting string:</p>

<pre><code>new_word = "".join("_" if letter in vowels else letter for letter in secret_word)
</code></pre>

<p>with exactly the same effect. Now, since you also have the dictionary <code>mapping</code>, getting the respective hint is easy, just supply the key <code>new_word</code> to <code>mapping</code> and it'll return the key. </p>

<p>A revised version of your code looks like  this:</p>

<pre><code>import random

Words = ("wallet", "canine")
Hints = ("Portable money holder", "Man's best friend")
mapping = dict(zip(Words, Hints))
vowels = "aeiouy"
secret_word = random.choice(Words)

new_word = "".join("_" if letter in vowels else letter for letter in secret_word)

print(new_word,"\t\t\t", d[secret_word])
</code></pre>

python python-3.x tuples