Help me with Python please (picture)

Dave Angel davea at davea.name
Sat Sep 28 13:16:57 EDT 2013


On 28/9/2013 12:17, dvghana at gmail.com wrote:

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

> 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))
> *******

First, I'd clean up the variable name, and use a for loop instead of a
while loop.

import string
import random

def random_characters(number):
    new_list = []
    for i in range(number):
        new_list.append(random.choice(string.ascii_lowercase))
    return "".join(new_list)


print(random_characters(8))

Then I'd probably replace the function body with:

def random_characters(number):
    return "".join([random.choice(string.ascii_lowercase) for i in
range(number)])

-- 
DaveA





More information about the Python-list mailing list