I am working through the Python Crash Course book and I don't know how to fix a problem with the Random Walk part. When I run the code, the command prompt gets stuck in a "processing" mode" which I cannot leave unless I close the window, i.e.
At first I thought that maybe I made the path too long but the code doesn't seem to work even if it is just 5 steps.
Here is the code for the class RandomWalk:
from random import choice
class RandomWalk():
"""A class to generate random walks."""
def __init__(self,num_points=5):
"""Initialize attributes of a walk"""
self.num_points = num_points
#All walks start at (0,0).
self.x_values = [0]
self.y_values = [0]
def fill_walk(self):
""""Calculate all the points in the walk"""
#Keep taking steps until the walk reaches the desired length
while len(self.x_values) < self.num_points:
#Decide which direction to go and how far to go there
x_direction = choice([1,-1])
x_distance = choice([0,1,2,3,4])
x_step = x_direction * x_distance
y_direction = choice([1,-1])
y_distance = choice([0,1,2,3,4])
y_step = y_direction * y_distance
#Reject moves that go nowhere
if x_step == 0 and y_step == 0:
continue
#Calculate the next x and y values
next_x = self.x_values[-1] + x_step
next_y = self.y_values[-1] + y_step
self.x_values.append(next_x)
self.y_values.append(next_y)
Here is the code to run RandomWalk:
import matplotlib.pyplot as plt
from random_walk import RandomWalk
#Make a random walk, and plot the points.
rw = RandomWalk(5)
rw.fill_walk()
plt.scatter(rw.x_values, rw.y_values, s=15)
plt(show)
I would expect the result of the code to be a matplot view that shows me a random 5 steps walk.
Thanks for any help!
You never update x_values
or num_points
in your while loop so you create an infinite loop.
I think you missed a tab on the last lines of the RandomWalk class