Python Forum
Breaking a loop in Multiple Random Walks
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Breaking a loop in Multiple Random Walks
#1
Happy Labor Day everyone!

Currently using Spyder(Python3.7)
I'm following an example from a textbook here:

import matplotlib.pyplot as plt

from random_walk import RandomWalk

#Generating multiple random walks
rw=RandomWalk()
rw.fill_walk()

#Plot the points in the walk.
plt.style.use('classic')
fig, ax = plt.subplots()
ax.scatter(rw.x_values, rw.y_values, s=15)
plt.show()

keep_running = input("Make another walk? (y/n): ")
if keep_running == 'n':
    break
Yes, the folder containing the file random_walk is chosen in the path and worked on single random walks. Here's the error:

Error:
SyntaxError: 'break' outside loop


Thanks guys!
Reply
#2
there is nothing else than what error already tells you - you can have break only in the body of loop. In your code there is no loop.
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#3
The loop is in the random_walk file. Here is the code:
#Creating a randomwalk() Class 

from random import choice

class RandomWalk:
    """A class to generate random walks"""
    
    def __init__(self, num_points=5000):                #5000 = default number of points in a walk
        """Initialize attributes of a walk."""
        self.num_points = num_points
        
        #All walks start at (0, 0)"""
        self.x_values = [0]
        self.y_values = [0]
        
#choosing directions
    def fill_walk(self):
        """Calculate all the points in the walk."""
        
        # Keep taking steps until the walk raches desired lengths.
        while len(self.x_values) < self.num_points:
            
            # Decide which direction to go and how far to go in that direction.
            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 steps that go nowhere
            if x_step == 0 and y_step ==0:
                continue
            
            #calculate the new position.
            x = self.x_values[-1] + x_step
            y = self.y_values[-1] + y_step
            
            self.x_values.append(x)
            self.y_values.append(y)
Reply
#4
it doesn't work like that :-)
you cannot "inject" your break in the loop inside fill_walk() method. Not to mention that by the time it reaches line 16, the fill_walk() method execution called on line 7 (given that you don't use threads) will be completed.
Think how to refactor your code, if you want to break out of the loop that is in that method. However I'm not sure it's that what you want. Isn't it supposed that you call fill_walk() multiple times and plot these. i.e. have a loop in the main code and call fill_walk() multiple times? The loop in fill_walk() is intended to produce a walk with desired len.
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#5
That's quite some food for thought. Kinda disappointing that textbooks contain code that doesn't really work, though perhaps I'm getting it wrong somewhere else. Thanks for the input, I'll try to figure something out.
Reply
#6
(May-01-2020, 09:48 AM)PythonGainz Wrote: Kinda disappointing that textbooks contain code that doesn't really work
is it really example from a textbook, verbatim?

OK, quick google search and it show it's from Python Crash Course, 2nd Edition: A Hands-On, Project-Based Introduction to Programming by Eric Matthes


Note that the example in the book has while True: just before your line 5 and rest of the code is in the loop body. This line is missing in your code. It does exactly what I expected - you are in loop and execute the rest of the code until you break out of it.
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#7
Oh man... I really think I'm too dumb for Python.....
Reply
#8
(May-01-2020, 02:16 PM)PythonGainz Wrote: Actually, the while true comes later, when "Styling the Walk", which I just saw.
Nope, it comes on page 318, section Generating Multiple Random Walks. This is just before next section Styling the Walk on page 319.

   
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#9
(May-01-2020, 02:31 PM)PythonGainz Wrote: Oh man... I really think I'm too dumb for Python.....
There is no such thing as "too dumb for Python", everyone learns at their own pace.
And please, in future don't remove post content.
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#10
Cheers man, I removed it cause I saw what I posted was wrong. The While True was there all the time, but printed in bold, so I thought it was part of the #comment.
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020