Python Forum

Full Version: Changing for loop to while loop
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Can someone help me out in changing this for loop to a while loop
hits=0.0
arrows=100
For i in range(arrows):
    Randx=random.uniform(-1,1)
    Randy=random.uniform(-1,1)
    if (randx**2+randy**2)<1:
        hits+=1.0
What have you tried? Post your attempt in Python code tags.
In case you are completely stuck, you will probably want to use a variable as a counter (for 100 arrows) and increment/decrement it in each iteration. And of course check for counter's value in the while loop condition.
The following link may help you with the while loop: http://www.pythonforbeginners.com/loops/...ile-loops/

Please note that Python is CASE SENSITIVE.

In your existing code, For should be for. According to the Python style guide (PEP8) randx and randy should be lower case. See https://www.python.org/dev/peps/pep-0008/ See the 'function and variable names section': https://www.python.org/dev/peps/pep-0008...able-names

You should probably add a debugging print statement to see if your code is working correctly. Maybe something like:
print(randx, randy, randx**2+randy**2, hits)
When testing code with random numbers, it is sometimes difficult to debug the code because each time you run the code, the random number sequence is different. For testing purposes you can add the following line at the beginning of your code (after the import statement) to generate the same random number sequence each time. The number inside the parentheses is the 'seed number' which you can change to any number you like. When you are done debugging, you can remove the line that seeds the random number generator.
random.seed(12345)
I hope this helps.

Lewis
General approach for such transforming is the following:

for item in some_iterable:
    # any python code here

# can be rewritten as:

while True:
    try:
        item = next(some_iterable)
    except StopIteration:
        break
    # any python code here