Hey guys, I'm new to Python and programming in general, and I've come across a problem that I can't quite figure out in my experimentation with the random module. So, basically, I want the following code to ask the user to input a word, and then randomly print a single letter from that word.

import random
word = raw_input("Enter a word: ")
wordsize = len(word)
randomnumber = random.randrange(0, wordsize)
print word[randomnumber]

Oddly, the program does what I want it to about half the time, while for the other half it simply prints "1". It also seems as if the larger the word I type in is, the more likely the program is to work. What's going on here? Any help would be appreciated, thanks.

If the word you enter is 'xp11' then it will do that.

BTW you don't have to subtract one from wordsize, randrange() work like range().

Give it a test:

import random

#word = raw_input("Enter a word: ")
word = "consumer"
wordsize = len(word)
for k in range(10):
    randomnumber = random.randrange(0, wordsize)
    print word[randomnumber]

The word I was entering was "Hello", typically. I realize that it works when 'word' is defined within the program, but why doesn't it work with user input? Try the code for yourself, it frequently prints "1" for some reason unknown to me.

Edit: It does seem to work with the For loop, but I don't really understand why. Try the following code without the for loop a few times, and you'll see what I mean.

word = raw_input("Enter a word: ")
wordsize = len(word)
randomnumber = random.randrange(0, wordsize)
print word[randomnumber]

Does your lower case letter L look like a 1?

It does on my screen.

I don't know what to tell you, man. I've run the code you provided in your first post about a dozen times giving it long and short words and I haven't been able to replicate the problem. One idea that comes to mind, though, is to have your program output what the random integer selected was. Then when your program puts out a 1, you can see if it is doing so every time the same random number is chosen.

Okay, this is what I tried ...

import random
word = raw_input("Enter a word: ")
wordsize = len(word)
randomnumber = random.randrange(0, wordsize)
c = word[randomnumber]
print c, c.isdigit()

"""
one result after entering hello -->
Enter a word: hello
l False  <--- this means that l is the letter l and not the number 1
"""

So it looks like your code is working then, right? Do you have any more questions about this?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.