Reputation: 23
I'm trying to get this homework done I've completed almost all of it besides formatting to make it look readable and this little problem I've been having, I can't seem to be getting this randrange()
to work properly. It works most of the time, but every so often I get the error at the bottom.
dict_of_strings = {
1:"PoopyPants", #my go-to programming word... i donno what to tell you...
2:"SleighBells", #i asked my girlfriend or the next two
3:"CookieMonster",
4:"bomb", #i have noidea how this one came to me
5:"Blellow", #when you mix blue and yellow, according to reece from Malcom in the Middle
6:"RandomWordOne", #because, random
7:"Flaccid", #theres a pattern to this word
8:"Solid", #maybe this is the pattern
9:"VaultOneHundredEleven", #FALLOUT4 HYPETRAIN
10:"SirDoctorMcFlippertonTheTwentySecondOfTheHouseOfLordProfessorSteveWilkerton" #this was a fun, convoluted phrase to come up with
}
def choice_is_rand(dict_of_strings):
rand_word = str(dict_of_strings[random.randrange(0,10)]) #did i get this range correctly? i've always had trouble. I thought I had it, but i guess not...
rand_backward = rand_word[::-1]
print(rand_word)
print(rand_backward.lower())
I'm trying to get the rand_word randrange to work, but I seem to be getting it wrong. My particular error is:
Traceback (most recent call last):
File "I:\User\My Documents\Komodo Projects\COP 1000\Module 11\Reverse the Word.py", line 116, in <module>
main()
File "I:\User\My Documents\Komodo Projects\COP 1000\Module 11\Reverse the Word.py", line 35, in main
choice_is_rand(dict_of_strings)
File "I:\User\My Documents\Komodo Projects\COP 1000\Module 11\Reverse the Word.py", line 73, in choice_is_rand
rand_word = str(dict_of_strings[random.randrange(0,10)])
KeyError: 0
Upvotes: 0
Views: 181
Reputation: 11585
You can either change your range choice to start at your first value, being 1
, or you can directly pick out the word with choice
# Select the word directly
random_word = random.choice(list(dict_of_strings.values()))
# Or select the key, and then access the word
random_word_index = random.choice(list(dict_of_strings.keys()))
random_word = dict_of_strings[random_word_index]
# As Pynchia pointed out, you can simply do the following without the
# need to fetch the keys, and cast them to a list.
# This will work on Python 3.5+, but not Python 3.4< or Python 2.7<
# in such case, you must make your keys start from zero, not one
random_word = random.choice(dict_of_strings)
Upvotes: 2
Reputation: 2157
Instead of this:
rand_word = str(dict_of_strings[random.randrange(0,10)])
Use this:
rand_word = str(dict_of_strings[random.randint(1, len(dict_of_strings))])
Two reasons:
Your keys start at 1 and randrange()
does not include the endpoint, while randint()
does, so starting at 0 causes an error about 10% of the time for you.
Getting the endpoint with len(dict_of_strings)
means you can use different dicts.
However, random.choice(dict_of_strings)
is more appropriate.
Upvotes: 0