Random Walk Simulation with Python

  • Share this:

Code introduction


The code uses the random module from the built-in Python library for random number generation and the random.choice() function to select a random direction for each step.


Technology Stack : The code utilizes the random module from Python's built-in library for random number generation, specifically the random.choice() function to select a random direction for each step.

Code Type : Function

Code Difficulty : Intermediate


                
                    
def random_walk(x, y, steps):
    import random
    directions = ['N', 'E', 'S', 'W']
    walk = [(x, y)]
    for _ in range(steps):
        direction = random.choice(directions)
        if direction == 'N':
            y += 1
        elif direction == 'E':
            x += 1
        elif direction == 'S':
            y -= 1
        elif direction == 'W':
            x -= 1
        walk.append((x, y))
    return walk