I have to make this game for my comp class, and I can't figure out how how break out of this loop. See, I have to play against the "computer," by rolling bigger numbers, and seeing who has the bigger score. But I can't figure out how to "break" from my turn, and transition to the computers turn. I need "Q" (quit) to signal the beginning of the computers turn, but I don't know how to do it.
ans=(R) while True: 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 if ans=='Q': print("Now I'll see if I can break your score...") break
Breaking Out of While Loops. To break out of a while loop, you can use the endloop, continue, resume, or return statement.
Answer. In Python, the main way to exit a loop is using the break statement. When the break statement runs in a loop, it will terminate that loop. However, one thing to keep in mind is that break statements will only terminate the innermost loop that it is run inside.
You can stop an infinite loop with CTRL + C . You can generate an infinite loop intentionally with while True . The break statement can be used to stop a while loop immediately.
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 I'll see if I can break your score...") break
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With