44

I have to make this game for my comp class, and I can't figure out how how break out of this loop.

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
1
  • Using break the way you are is fine, but you have to type exactly Q. q won't work for example. Is the first line supposed to say ans=('R')? you don't need it anyway Commented Jan 30, 2013 at 0:28

5 Answers 5

31

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
Sign up to request clarification or add additional context in comments.

2 Comments

Please correct me if needed- break sends a False signal to stop the while loop?
@SIslam Kind of. break stops the while loop, but there isn't a 'False signal': while means 'loop while the expression following the while statement evaluates as True', so if what comes after while is True itself, while will loop forever; break means 'stop looping right now' and works any loop, including both while and for loops.
13

I would run the loop until ans is 'Q' like this:

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

Comments

9

Don't use while True and break statements. It's bad programming.

Imagine you come to debug someone else's 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. You'd 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.

6 Comments

Unless you were using a short example...
Consider rephrasing "Don't use while True and break statements. It's bad programming." While I try to avoid them as a general rule, many times I have simplified logic structures in a while loop simply by using a single break statement. While I agree that 15 break statements scattered through a while loop isn't great, I would posit that neither is 200 lines of code.
There are cases where ''while True:' and 'break' are the right thing to do. Sometimes you can't/shouldn't do the 'while' test in the while statement but need to do it within the loop, therefore you need a 'break'
@Ribo You can write your own answer. See meta.stackoverflow.com/a/362673
I was trying to improve the answer by indicating that there are appropriate cases to use 'while True / break' I think that saying that it is flatly 'bad' is oversimplifying and incorrect. -- expression assignment was an example, there are other operations like '.pop()' that have side effects.
|
3
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
    else:
        print("Now I'll see if I can break your score...")
        ans = False
        break

Comments

1

Walrus operator (assignment expressions added to python 3.8) and while-loop-else-clause can do it more pythonic:

myScore = 0
while ans := input("Roll...").lower() == "r":
    # ... do something
else:
    print("Now I'll see if I can break your score...")

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.