Python Forum
Changing for loop to while loop - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Changing for loop to while loop (/thread-9494.html)



Changing for loop to while loop - Slth02 - Apr-12-2018

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



RE: Changing for loop to while loop - j.crater - Apr-12-2018

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.


RE: Changing for loop to while loop - ljmetzger - Apr-12-2018

The following link may help you with the while loop: http://www.pythonforbeginners.com/loops/python-for-and-while-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/#function-and-variable-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


RE: Changing for loop to while loop - scidam - Apr-13-2018

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