title: Simulating a random walk in Python
body: <p>I am using Python 3. My code below attempts to simulate N steps of a <a href="https://en.wikipedia.org/wiki/Random_walk" rel="nofollow noreferrer">random walk</a> in 3 dimensions. At each step, a random direction is chosen (north, south, east, west, up, down) with 1/6 probability each and a step of size 1 is taken in that direction. The new location is then printed. The starting location is the origin (0,0). </p>
  
  <p>Even though there are no error messages, <strong>the code does not work</strong>. We should move <strong>only</strong> one step either in x, y or z. However, in the output, I see that sometimes I don't move at all or sometimes I move in more than one direction. </p>
  
  <p>Here is my code:</p>
  
  <pre><code>import random
  
  N = 30
  
  n = random.random() 
  
  x = 0
  y = 0
  z = 0
  count = 0
  
  while count &lt;= N:
  
      if n &lt; 1/6:
          x = x + 1          
          n = random.random()
      if n &gt;= 1/6 and n &lt; 2/6:
          y = y + 1           
          n = random.random() 
      if n &gt;= 2/6 and n &lt; 3/6:
          z = z + 1           
          n = random.random() 
      if n &gt;= 3/6 and n &lt; 4/6:
          x = x - 1           
          n = random.random() 
      if n &gt;= 4/6 and n &lt; 5/6:
          y = y - 1          
          n = random.random() 
      if n &gt;= 5/6:
          z = z - 1          
          n = random.random()
  
      print("(%d,%d,%d)" % (x,y,z))
      count = count + 1
  
  print("squared distance = %d" % (x*x + y*y + z*z))
  </code></pre>
  
  <p>How do you think I can fix the problem?</p>
  
  <p>Thanks a lot.</p>