Help me with Python please (picture)

dvghana at gmail.com dvghana at gmail.com
Sat Sep 28 12:17:54 EDT 2013


On Saturday, September 28, 2013 12:43:42 AM UTC, jae... at gmail.com wrote:
> http://imgur.com/E6vrNs4
> 
> 
> 
> 
> 
> Can't seem to be getting an output.

All the comments about using an image to ask for help over here is extremely valid so I hope you accept it in good faith. I am a noob like you so I can tolerate it and see if I can help you.

So here we  go:
1. random.randit will only return an integer but it sounds to me like you are trying to return one of the elements in "chars"

If my understanding is correct try using random.choice instead.

To return a random character from the alphabets you can try:

>> import string
>> char = random.choice(string.ascii_lowercase) 
   #string.ascii_uppercase for uppercace

2. you may not need the main() function.
and you didn't have any 'print' statement so when you run the code you won't see anything. You are simply generating random characters and throwing them away

try:
print (random_characters(8))

3. but if you run the code as it stands it won't generate 8 random charaters so you'll actually have to be appending it on a list.

So instead of:
new_string = ''
try:
new_string = []

4. Finally, join the elements in the list once they are generated like this:
    return "".join(new_string)
but don't forget to append each character anytime the loop runs this way:
    new_string.append(random.choice(string.ascii_lowercase))
    
Overall I wrote my own version of the code and this is what I got:


******************
import string
import random

def random_characters(number):
    i = 0
    new_string = []

    while (i < number) :
        new_string.append(random.choice(string.ascii_lowercase))
        i = i + 1
    return "".join(new_string)


print(random_characters(3))
*******



More information about the Python-list mailing list