Python Forum
int is not iterable - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: int is not iterable (/thread-21278.html)



int is not iterable - qerrrr - Sep-22-2019

import random
    easier = ["joke","haze","kick","apex","buff","exam","mope","pick"]
    words = (random.choice(easier))
    first=input ("Ok choose your first letter")
    for char in words:
        amount = words.count(char)
        if first in amount >= 1:
            print(amount)
I'm trying to make hangman, but I'm trying to find out how to make it check how many times a letter(that's inputed by the user)is in the randomly generate word. Please help me. Smile


RE: int is not iterable - metulburr - Sep-22-2019

It would be more simple to just first make a database of the count of letters in your list. Then compare the users letter with the database


words = ["joke","haze","kick","apex","buff","exam","mope","pick"]
d = {}

for word in words:
    for letter in word:
        count = word.count(letter)
        try:
            d[word][letter] = count
        except KeyError:
            d[word] = {}
            d[word][letter] = count
print(d)
Output:
{'joke': {'j': 1, 'o': 1, 'k': 1, 'e': 1}, 'haze': {'h': 1, 'a': 1, 'z': 1, 'e': 1}, 'kick': {'k': 2, 'i': 1, 'c': 1}, 'apex': {'a': 1, 'p': 1, 'e': 1, 'x': 1}, 'buff': {'b': 1, 'u': 1, 'f': 2}, 'exam': {'e': 1, 'x': 1, 'a': 1, 'm': 1}, 'mope': {'m': 1, 'o': 1, 'p': 1, 'e': 1}, 'pick': {'p': 1, 'i': 1, 'c': 1, 'k': 1}}
Then you just input what the user into the dictionary to give the count
import random
words = ["joke","haze","kick","apex","buff","exam","mope","pick"]
d = {}

for word in words:
    for letter in word:
        count = word.count(letter)
        try:
            d[word][letter] = count
        except KeyError:
            d[word] = {}
            d[word][letter] = count
print(d)
chosen = random.choice(words)
search = input(f'search for letter in {chosen}: ')
print(d[chosen][search])