How to break out of while loop in Python?

How to break out of while loop in Python?

A couple of changes mean that only an R or r will roll. Any other character will quit

import random

while True:
    print(Your score so far is {}..format(myScore))
    print(Would you like to roll or quit?)
    ans = input(Roll...)
    if ans.lower() == r:
        R = np.random.randint(1, 8)
        print(You rolled a {}..format(R))
        myScore = R + myScore
    else:
        print(Now Ill see if I can break your score...)
        break

What I would do is run the loop until the ans is Q

ans=(R)
while not ans==Q:
    print(Your score is so far +str(myScore)+.)
    print(Would you like to roll or quit?)
    ans=input(Roll...)
    if ans==R:
        R=random.randint(1, 8)
        print(You rolled a +str(R)+.)
        myScore=R+myScore

How to break out of while loop in Python?

Dont use while True and break statements. Its bad programming.

Imagine you come to debug someone elses code and you see a while True on line 1 and then have to trawl your way through another 200 lines of code with 15 break statements in it, having to read umpteen lines of code for each one to work out what actually causes it to get to the break. Youd want to kill them…a lot.

The condition that causes a while loop to stop iterating should always be clear from the while loop line of code itself without having to look elsewhere.

Phil has the correct solution, as it has a clear end condition right there in the while loop statement itself.

Leave a Reply

Your email address will not be published. Required fields are marked *