Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to break out of while loop in Python?

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 
like image 957
Ninja Avatar asked Jan 30 '13 00:01

Ninja


People also ask

How do you exit a while loop?

Breaking Out of While Loops. To break out of a while loop, you can use the endloop, continue, resume, or return statement.

How do you get out of a loop in Python?

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.

How do I stop while true?

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.


1 Answers

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 
like image 104
John La Rooy Avatar answered Sep 28 '22 17:09

John La Rooy