Firstly, your return
is inside the loop, so you don't ever loop several times. Change it to
def random_characters(number):
i = 0
new_string = ''
while (i < number) :
new_string = random.choice(string.ascii_lowercase)
i = i + 1
return new_string # <<< Dedent
random_characters(3)
#>>> 'c'
Then you need to actually build new_string
, not just set it each time. Build a list
and then "".join
it:
def random_characters(number):
i = 0
letters = [] # Place to put the letters
while (i < number) :
letters.append(random.choice(string.ascii_lowercase)) # <<< Add the letter
i = i + 1
return "".join(letters) # <<< Join the letters into one string
random_characters(3)
#>>> 'lgp'
Then you should use for i in range(number)
instead of the while
loop:
def random_characters(number):
letters = []
for i in range(number): # <<< Deals with i for you.
letters.append(random.choice(string.ascii_lowercase))
return "".join(letters)
random_characters(3)
#>>> 'xay'
And you can use a shortened version with a list comprehension:
def random_characters(number):
# MAGIC!
letters = [random.choice(string.ascii_lowercase) for i in range(number)]
return "".join(letters) # <<< Join the letters into one string
random_characters(3)
#>>> 'yby'
If you're wanting to run this, you have several choices. Either you can run this in the interactive interpreter:
%~> python -i random_characters.py
>>> random_characters(3)
'zgp'
or you can tell it to print
the result inside the file:
print(random_characters(3)) # Python 3
print random_characters(3) # Python 2