Note that there are some explanatory texts on larger screens.

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

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload