0

I am currently learning the random walk on Python, I came across the sample code that I couldn't explain please help me to clarify this

My question is that why does x no need to be put in the loop but the code is still able to operate. The other question is regarding the initial value of the loop step = random_walk[-1].

Thanks!

# Numpy is imported, seed is set

# Initialize random_walk

random_walk = [0]

# Complete the ___
for x in range(100) :   # the first question is at here.
    # Set step: last element in random_walk
    step = random_walk[-1] # the other question is at here.
 
    # Roll the dice
    dice = np.random.randint(1,7)

    # Determine next step
    if dice <= 2:
        step = step - 1
    elif dice <= 5:
        step = step + 1
    else:
        step = step + np.random.randint(1,7)

    # append next_step to random_walk
    random_walk.append(step)

# Print random_walk
print(random_walk)
James Huang
  • 63
  • 1
  • 10
  • 1
    Using the loop variable in the body of the loop is optional. The loop still runs the expected number of times.Usually in such cases you should use `_` as the loop variable. – rdas Oct 23 '20 at 17:11
  • 1
    `random_walk[-1]` is just the last element of the list `random_walk`. See: https://www.digitalocean.com/community/tutorials/how-to-index-and-slice-strings-in-python-3 – rdas Oct 23 '20 at 17:13
  • Thank you @rdas for reminding me this basic concept. Ideally, I should use `for _ in range(100)`? – James Huang Oct 23 '20 at 17:18
  • Yes. It's the convention. – rdas Oct 23 '20 at 17:19
  • Thank you, this really helps me a lot! – James Huang Oct 23 '20 at 17:25

0 Answers0